Bash – Trimming a String Stored in a Variable

Assume we have this bash variable  (The colors will be used to show which parts of the string are not removed)

x=”tic toc tic toc

We have the following manipulations available:

${x%toc*}

Removes the shortest match of the pattern “toc*” from the end of the string.

${x%%toc*}

Removes the longest match of the pattern “toc*” from the end of the string.

${x#*tic}

Removes the shortest match of the pattern “*tic” from the beginning of the string.

${x##*tic}

Removes the longest match of the pattern “*tic” from the beginning of the string.

Example

$ echo ${x%toc*}
tic toc tic
$ echo ${x%%toc*}
tic
$ echo ${x#*tic}
toc tic toc
$ echo ${x##*tic}
toc

Enjoy :-)