Linux Rename File and Directory

There are other commands to rename a directory like ‘mv’, but ‘rename’ command is more advanced than others. It is rarely used and it works differently on different Linux distros. We are using Debian/Ubuntu for examples.

Normally speaking, renaming a file is not big of a task, but when it comes to renaming a large group of files at once then it becomes difficult to rename it using ‘mv’ command. In such cases, it is advisable to use ‘rename’ command instead on ‘mv’ command. It is capable of converting upper case files to lower case files and vice versa. It can also overwrite files using perl expressions as it is a part of perl script.

Basic syntax:

rename 's/old-name/new-name/' files

The expression ‘s/old-name/new-name/’ is the perl compatible regular expression (PCRE) which is used to rename files. Let us understand using an example of basic rename command:

In the following example, we are converting all the files ending with ‘.txt’ into the files ending with ‘.pdf’.

Example:

codes@w3schools:~/Downloads$ ls
 
file1.txt file3.txt file5.txt file7.txt file9.txt
 
file2.txt file4.txt file6.txt file8.txt
 
codes@w3schools:~/Downloads$
 
codes@w3schools:~/Downloads$ rename 's/\.txt$/\.pdf/' *.txt
 
codes@w3schools:~/Downloads$
 
codes@w3schools:~/Downloads$ ls
 
file1.txt file3.txt file5.txt file7.txt file9.txt
 
file2.txt file4.txt file6.txt file8.txt
 
codes@w3schools:~/Downloads$

Let us take another example, here we are converting file into document for all the files ending with .pdf.

Example:

codes@w3schools:~/Downloads$ ls
 
file1.pdf file3.pdf file5.pdf file7.pdf file9.pdf
 
file2.pdf file4.pdf file6.pdf file8.pdf
 
codes@w3schools:~/Downloads$
 
codes@w3schools:~/Downloads$ rename 's/file/document/' *.pdf
 
codes@w3schools:~/Downloads$
 
codes@w3schools:~/Downloads$ ls
 
document1.pdf document.pdf document.pdf document.pdf document.pdf
 
document.pdf document.pdf document.pdf document.pdf
 
codes@w3schools:~/Downloads$

rename option:

The ‘rename’ option has some optional arguments but a mandatory perl expression which is used with every option and guides it how to work.

Option Function
rename -n It checks changes before running the command.
rename -v It prints the output.
rename (a-z)(A-Z)/ (A-Z)(a-z) It converts into upper case/lower case.
rename -f It forcefully over write the existing files.

 

Content Protection by DMCA.com