Rename Multiple Files In Linux using mmv command
- mmv moves (or copies, appends, or links, as specified) each source file matching a from pattern to the target name specified by the to pattern.
yum install mmv
Let us say, you have the following files in your current directory.
$ ls a1.txt a2.txt a3.txt
Now you want to rename all files that starts with letter “a” to “b”. Of course, you can do this manually in few seconds. But just think if you have hundreds of files and want to rename them? It is quite time consuming process. Here is where mmv command comes in help.
To rename all files starting with letter “a” to “b”, simply run:
$ mmv a\* b\#1
Let us check if the files have been renamed or not.
$ ls b1.txt b2.txt b3.txt
As you can see, all files starts with letter “a” (i.e a1.txt, a2.txt, a3.txt) are renamed to b1.txt, b2.txt, b3.txt.
Let’s understand the mmv command
In the above example, the first parameter (a\*) is the ‘from’ pattern and the second parameter is ‘to’ pattern ( b\#1 ). As per the above example, mmv will look for any filenames staring with letter ‘a’ and rename the matched files according to second parameter i.e ‘to’ pattern. We use wildcards, such as ‘*’, ‘?’ and ‘‘, to match one or more arbitrary characters. Please be mindful that you must escape the wildcard characters, otherwise they will be expanded by the shell and mmv won’t understand them.
The ‘#1′ in the ‘to’ pattern is a wildcard index. It matches the first wildcard found in the ‘from’ pattern. A ‘#2′ in the ‘to’ pattern would match the second wildcard and so on. In our example, we have only one wildcard (the asterisk), so we write a #1. And, the hash sign should be escaped as well. Also, you can enclose the patterns with quotes too.
Rename the file extension using mmv
You can even rename all files with a certain extension to a different extension. For example, to rename all .txt files to .doc file format in the current directory, simply run:
$ mmv \*.txt \#1.doc
Here is an another example. Let us say you have the following files.
$ ls abcd1.txt abcd2.txt abcd3.txt
You want to replace the the first occurrence of abc with xyz in all files in the current directory. How would you do?
$ mmv '*abc*' '#1xyz#2'
Please note that in the above example, I have enclosed the patterns in single quotes.
Let us check if “abc” is actually replaced with “xyz” or not.
$ ls xyzd1.txt xyzd2.txt xyzd3.txt
See? The files abcd1.txt, abcd2.txt, and abcd3.txt have been renamed to xyzd1.txt, xyzd2.txt, and xyzd3.txt.
Another notable feature of mmv command is you can just print output instead of renaming the files using -n option like below.
$ mmv -n a\* b\#1 a1.txt -> b1.txt a2.txt -> b2.txt a3.txt -> b3.txt
This way you can simply verify what mmv command would actually do before renaming the files.For any query or issue, feel free to discuss on http://discuss.eduguru.in