Everything you need to know about strings manipulation in Bash

,

One of the best things in Bash is the extensive tools we can use to manipulate strings. you can extract substrings , replace or delete them, and do much more.
This will be our string to manipulate for this tutorial:



#!/bin/sh
str=/home/mosaid/Documents/Bash/Bashstrings.sh
#   0123456789.....
#   0-based indexing.


Get Length of string



echo ${#str}        #42


Get 5 chars starting from 0



echo ${str:0:5}      # /home


Get everything after the 5th char



echo ${str:5}      # /mosaid/Documents/Bash/Bashstrings.sh


backward positioning: get the last 14 chars


we use parentheses or a space to delimit the negative sign for the position parameter when we are backward positioning:


echo ${str:(-14)}      # Bashstrings.sh
echo ${str: -14}       # Bashstrings.sh


substrings: forward search


remove everything before ( including ) the first occurrence of "Bash" :



echo ${str#*Bash}      # /Bashstrings.sh

remove everything untill (and including) the last occurrence of "Bash" :



echo ${str##*Bash}      # strings.sh

we can use the same to extract the extension: remove everything until the last dot "."
or to extract the file name from the path by removing everything untill the last "/":


echo ${str##*.}      # sh
echo ${str##*/}      # Bashstring.sh


substrings: backward search


starting from the end remove everything after (including) the word "Bash":


echo ${str%Bash*}      # /home/mosaid/Documents/Bash/

we can use it to extract the directory path :
starting from the end, removing everything after the first occurrence of "/"


echo ${str%%/*}      # /home/mosaid/Documents/Bash/


substrings: replace


first example : replace the first occurrence of "Bash" with "Shell Scripting"
second example: replace all occurrences of "Bash" with "Shell"


echo ${str/Bash/Shell Scripting}    # /home/mosaid/Documents/Shell Scripting/Bashstrings.sh
echo ${str//Bash/Shell}             # /home/mosaid/Documents/Shell/Shellstrings.sh

if we want to use the backward slash "/" as a pattern we need to escape it with a forward slash "\":
replace all "/" with "@"


echo ${str//\//@}       # @home@mosaid@Documents@Bash@Bashstrings.sh

we can make some/all chars uppercase or lowercase:


str="Hello, Welcome to LINUX, Bash strings"

#convert the first char to uppercase
echo ${str^}

#convert all chars to uppercase
echo ${str^^}

#convert the characters c,s and m to uppercase
echo ${str^^[csm]}

#convert the first char to lowercase
echo ${str,}

#convert all chars to lowercase
echo ${str,,}

#convert the characters N,U and S to lowercase
echo ${str,,[NUS]}



delimit string and divide it into variables


Here, the delimitter (separator) is the comma ,



str="Hello, Welcome to LINUX, Bash strings"

IFS=, read -r x y z <<< "$str"

echo x = $x         # Hello
echo y = $y         # Welcome to LINUX
echo z = $z         # Bash strings


delimit string and divide it into an array



str="Hello, Welcome to LINUX, Bash strings"

IFS=, read -ra arr <<< "$str"

echo ${arr[0]}         # Hello
echo ${arr[1]}         # Welcome to LINUX
echo ${arr[2]}         # Bash strings


With these tools we can manipulate our strings in any way we want, however we might face a situation much complicated where these native Bash strings manipulation tools will not be sufficient, at this point we can use some much more powerful commands like sed or awk.

Buy me A Coffee

Comments:

  • Ultimate

    Hi, would you like more business leads at a lower cost? Currently http://GetMoreBusinessLeadsNow.com is offering our popular unlimited lead generation software package - at a reduced price for a limited time. Download and install now to be building databases of leads in minutes: http://GetMoreBusinessLeadsNow.com The Ultimate Lead Generation Pack works by automatically visting yellow page directories and building a database according to your search terms. Other software in the pack then finds emails, phone numbers, and other details for that database. The results can be used for email, cold-calling, direct mail, or to sell immediately - priced per lead. Runs on Windows, Mac, and Linux with multiple job and VPN/proxy support. Similar software retails for over $100 with less features. This pack is only available on sale as a short promotional offer, please download now if at all interested. Click Here: http://GetMoreBusinessLeadsNow.com Have a Great Day, The Ultimate Lead Gen

  • GetABusinessLoanNow

    Hi, do you know that http://GetABusinessLoanNow.info can help your business get funding for $2,000 - $350K Without high credit or collateral. Find Out how much you can get by clicking here: http://GetABusinessLoanNow.info Requirements include your company being established for at least a year and with current gross revenue of at least 120K. Eligibility and funding can be completed in as fast as 48hrs. Terms are personalized for each business so I suggest applying to find out exactly how much you can get on various terms. This is a completely free service from a qualified funder and the approval will be based on the annual revenue of your business. These funds are completely Non-Restrictive, allowing you to spend the full amount in any way you require including business debt consolidation, hiring, marketing, or Absolutely Any Other expense. If you need fast and easy business funding take a look at these programs now as there is limited availability: http://GetABusinessLoanNow.

: We will never share your email