String manipulation in Linux shell scripting

This topic covers various ways in which we can manipulate strings in BASH scripting.

Finding the length of the variable’s value
All of below commands will print the length of the value of variable “city”

city=Brisbane
echo ${#city}
echo `expr length $city`
echo `expr “$city” : ‘.*’`
Finding the sub string position

Below commands print the length of matching substring
echo `expr match “$city” ‘Bris’`
echo `expr “$city” : ‘Bris*’`
Finding the index of first character

echo `expr index “$city” b233`
echo `expr index “$city” 5n`

Extract the portion of the string

  1. echo ${city:0}
  2. echo ${city:1}
  3. echo ${city:2:4}
  4. echo ${city:(-4)}
  5. echo ${city: -4}

You can also use expr to return the sub string.

echo `expr substr $city 1 3`
echo `expr substr $city 2 4`
Extracting arguments of the script

echo ${*:2}
echo ${@:2}
echo ${*:1:2}
Getting matched pattern

echo `expr match “$city” ‘\(.*sb\)’`
echo `expr “$city” : ‘\(.*sb\)’`
Delete the shortest and longest match from the beginning of the string

echo ${stringZ#a*C}
echo ${stringZ##a*C}
Delete the shortest and longest match from the end of the string

${city%b}
${city%%s}
Replace the sub string

${string/substring/replacement}
${string//substring/replacement}

echo ${city/bane/boon}

You may also like...