String Manipulation in bash script

OperatorExplanation
${* variable* #* pattern* }Delete the shortest part of * pattern* that matches the beginning of * variable* ‘s value. Return the rest.
${* variable* ##* pattern* }Delete the longest part of * pattern* that matches the beginning of * variable* ‘s value. Return the rest.
${* variable* %* pattern* }Delete the shortest part of * pattern* that matches the end of * variable* ‘s value.Return the rest.
${* variable* %%* pattern* }Delete the longest part of * pattern* that matches the end of * variable* ‘s value.Return the rest.
The * pattern* s can be filename wildcard characters: ` *` , ` ?` , and ` []` ; with string editing operators, wildcards match strings in the same way they match filenames. (These are not * sed* -like regular expressions.) The first two operators, with ` #` , edit variables from the front. The other two, with ` %` , edit from the end. Here’s a system for remembering which does what: you put a number sign (` #` ) at the * front* of a number and a percent sign (` %` ) at the * end* of a number.

Time for some examples. The variable * var* contains * /a/b/c/d/e.f.g* :

<strong> Expression</strong><strong> Result</strong> ${var} /a/b/c/d/e.f.g ${var#/*/} b/c/d/e.f.g ${var##/*/} e.f.g ${var%.*} /a/b/c/d/e.f ${var%%.*} /a/b/c/d/e ${var%%/*/} /a/b/c/d/e.f.g ${var%%/*} ${var%/b*} /a ${var%%/b*} /a

PATH variable is a string separated by colons ( : ). Let’s say you want to remove the last directory from the system path and add $HOME/bin in place of the last directory. You’d type this command, or put a line like this in your * .profile* :

PATH=${PATH%:*}:$HOME/bin

Because the ${PATH%:*} has a single % , that operator removes the least it can: just the last colon plus the directory name after it. After string editing, the rest of the * PATH* has :$HOME/bin appended to it. The new value is saved as the new * PATH* .