Categories
Coding

Bash Parameter Substitution

More Bash Trickery

There is one neat trick that the Bash shell offers that I occasionally find very useful. However, usually when I go to use it, it’s been just long enough for me to forget how to do it. So here it is, so I know how to find it.

It’s called parameter substitution, and it works like this (paraphrased from the Advanced Bash Scripting Guide):

${var#Pattern}, ${var##Pattern} – Removes from $var the shortest/longest part of $Pattern that matches the front end of $var.

${var%Pattern}, ${var%%Pattern} – Remove from $var the shortest/longest part of $Pattern that matches the back end of $var.

I normally use it when I want to strip the file extension from a set of files and replace it with another, as part of an overall process like so:

for file in $(ls *.DAT); do mv $file ${file%.DAT}.ABC; done

will move all .DAT files in the current directory to files with a .ABC extension instead.

Leave a Reply