Objective: Rename multiple files in a directory on Unix or Linux.
One of the easiest ways to rename multiple files on Unix or Linux is by using the rename
command. This is typically a Perl script. Let’s say we have the following 5 files in a directory:
1 2 3 4 5 6 7 |
$ ls -l total 0 -rw-r--r-- 1 root root 0 Sep 6 15:10 foo1.txt -rw-r--r-- 1 root root 0 Sep 6 15:10 foo2.txt -rw-r--r-- 1 root root 0 Sep 6 15:10 foo3.htm -rw-r--r-- 1 root root 0 Sep 6 15:10 foo4.htm -rw-r--r-- 1 root root 0 Sep 6 15:10 foo5.log |
To rename the *.htm
files to *.html
, we can use the following syntax.
1 |
$ rename "s/\.htm/\.html/" *.htm |
The first argument is a Perl regular expression. The files are renamed according to the rule specified in the regular expression. The files to be renamed are specified in the second argument. Note that the syntax below would also work if you want to rename *.htm
files to *.html
. It says match the end of string and append an ‘l
‘.
1 |
$ rename "s/\$/\l/" *.htm |
Another command for renaming files is rename.ul
. It takes in three arguments. To rename *.htm
files to *.html
, we can use the following syntax.
1 |
$ rename.ul .htm .html *.htm |
The first occurrence of .htm
(1st argument) will be replaced with .html
(2nd argument) for all *.htm
files (3rd argument).
If both rename
and rename.ul
commands are not available, you can fallback to POSIX or bash shell for renaming files as long as it supports parameter substitution. To rename *.htm
files to *.html
using POSIX shell parameter substitution, we can use the following for loop to do the job.
1 |
$ for file in *.htm ; do mv $file ${file/.htm/.html} ; done |
Another utility for renaming files is mmv
. To install mmv
on a Debain based Linux distribution, use:
1 |
$ sudo apt-get install mmv |
To rename *.htm
files to *.html
using mmv
, use the following syntax.
1 |
$ mmv \*.htm \#1.html |
The first parameter is the search pattern. mmv
looks for any filenames ending with .htm
. The asterisk is a wildcard and just as in most shells, it matches one or more arbitrary characters (You can also use a question mark to match just a single character). Note that you should escape asterisks and question marks to prevent your shell from expanding them. The second parameter is the target filename. Every wildcard that matched in the search pattern can be inserted here by writing a hash sign followed a number. The number is that of the wildcard, counting from the left: the first wildcard becomes #1
, second #2
and so on. We have just one wildcard (the asterisk), so we write a #1
.
The mmv
tool is a lot more powerful. It can also perform uppercase and lowercase conversion. To rename *.htm
files to *.html
and convert file names to uppercase or lowercase, use the following syntax.
1 |
$ mmv \*.htm \#u1.html |
1 |
$ mmv \*.htm \#l1.html |
The #u1
converts the matched wildcard to uppercase and #l1
converts the wildcard to lowercase.