09 April 2015

Once for a while, we need to rename a number of files. This can of course be easily done with a trivial shell script (or in Emacs dird mode). However, in fact, there is already an even handier command line tool called rename to cope with that.

The usage is simple. To rename string "from" to "to" in file1, file2 etc., simply run

rename from to file1 file2 ...

In fact, we do not usually explicitly list every file to be renamed since we have file name glob!. Here is an example which renames all html files' extension from ".html" to ".htm".

rename html htm *.html

Please note that this tool does not only work with suffix. It replaces the "from" string in any place in the file names. See the below for an example.

$ ls *env*
smallenv.beg1  smallenv.beg2  smallenv.common  smallenv.proxyg1  smallenv.proxyg2
$ rename small set *env*
$ ls *env*
setenv.beg1  setenv.beg2  setenv.common  setenv.proxyg1  setenv.proxyg2

Caveat

You should be really cautious with "unexpected" occurrence of "from" string in file names since "rename" replaces the first and only the first occurrence of "from" in the file names. Note that in the following example the file name suffix is NOT changed.

$ ls
how_html_generated.html

$ rename html htm *

$ ls
how_htm_generated.html


blog comments powered by Disqus