BASH Substring manipulation

Strip Last Character

Command
Description

${string$?}
Returns the string minus the final character

String Length

Command
Description

${#string}
Returns the length of the string

Substring Extractions

Command
Description

${string:position}
${string:position:length}

Extracts substring from $string at $position. If the $string parameter is "*" or "@", then this extracts the positional parameters, starting at $position.

 

 

 

 

 

The last character of a string

string=hello
echo ${string: -1}
o

Substring Removal

Command
Description

${string#substring} 
Deletes shortest match of $substring from front of $string.

${string##substring}   
Deletes longest match of $substring from front of $string.

${string%substring} 
Deletes shortest match of $substring from back of $string.

${string%%substring}

Deletes longest match of $substring from back of $string.

Substring Replacement

Command
Description

${string/substring/replacement}

Replace first  match of $substring with $replacement.

${string//substring/replacement}
Replace all matches of $substring with $replacement.

${string/#substring/replacement}
If $substring matches front end of $string, substitute $replacement for $substring.

${string/%substring/replacement}
If $substring matches back end of $string, substitute $replacement for $substring.

 

 

 

 

 

 

 

BASH_REMATCH example

string=$( date +%T )

if [[ "$string" =~ ^([0-9][0-9]):([0-9][0-9]):([0-9][0-9])$ ]]; then
printf 'Got %s, %s and %s\n' \
"${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" "${BASH_REMATCH[3]}"
fi