String Manipulation in bash script
| Operator | Explanation |
|---|---|
| ${* 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. |
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* .