Saturday, February 13, 2010

Mass rename/move in bash

for i in *.HTM;
do mv $i `basename $i HTM`html;

There are a number of components to this mini hack.

First is the for loop. This is pretty straightforward if you know bash path regular expressions. The regex *.HTM is expanded to make a list of all files in the current directory that end in HTM. Note that this is case sensitive in Linux. Then we itereate over this list.
The meat of the loop is in the do part. We mv the original name to a name constructed by the following expression:

`basename $i HTM`html

The backticks means run the command in the backticks and use the output.

basename does two things here. It strips away the directory part of the path. In this case, there is none. The important part is the HTM argument to basename which means that we want to strip away the HTM suffix. For example:

basename readme.txt txt

will return


Note the period is kept.
Then doing this:

`basename $i HTM`html

Will return the basenemt concatenated with html. This is how we do string concatenation in bash. See previous article: String concatenation in bash.

Put that all together, we are able to do a mass rename/move in bash. Note that if we want to do more complicated pattern matching and renaming, we probably would have to do it in Python or Perl.

No comments: