String Processing with Bash
There are various tools built into bash that enable you to manipulate a variable or string which come in handy when writing shell scripts. Here are a few notable ones:
Find the length of a string
${#string}
Get a Substring from a String
${string:pos} or ${string:pos:len}
Removing Substrings from a String
${string#substr}
${string%substr}
${string##substr}
${string%%substr}
Some examples
Here’s a few examples of how you can process a variable that points to an absolute path of a file and shows how to extract certain parts of said file’s path:
var=/home/user/code/blogstuff/index.html.j2
echo ${var} # => /home/user/code/blogstuff/index.html.j2
echo ${var#*.} # => html.j2
echo ${var##*.} # => j2
echo ${var%/*.*} # => /home/user/code/blogstuff
Replace a Substring of a String
${string/pattern/substr} # => Replaces the 1st match found
${string//pattern/substr} # => Replaces all of the matches found
Replace the Beginning or End of a String
${string/#pattern/substr}
${string/%pattern/substr}
file=${var##/*/} # => index.html.j2
echo ${file/#index/fubar} # => fubar.html.j2
echo ${file/%j2/fubar} # => index.html.fubar
Tags: cli, bash, shell-scripting, motd