HOWTO: Renaming a group of files on your Linux machine
Posted : July 15, 2004 at 1:45 pm [America/Los_Angeles]
Found myself confronted with another pesky problem this morning.
Goal:
Rename a group of files in a folder (and possibly sub-folders)
Example:
You’ve a folder which has files looking like this:
[user@myhost tmp]> ls test1.txt test2.txt test3.txt readme.txt
Let’s say you want to rename the files starting with test as blah1.txt, blah2.txt and blah3.txt respectively.
Solution:
Approach 1: Using ‘rename’ command
In RedHat distribution, there is a utility called rename. You can use it as follows:
[user@host tmp]> ls test1.txt test2.txt test3.txt readme.txt [user@host tmp]> rename test blah test*.txt [user@host tmp]> ls blah1.txt blah2.txt blah3.txt readme.txt
Basically, rename will rename the specified files (test*.txt) by replacing the first occurrence (and first occurence only) of test in their name by blah. In other words, the command-line parameters of rename are:
- pattern of the filename that needs to be replaced/changed (in our example, test)
- pattern that #1 (found above) will be replaced with (in our example, blah)
- all files that need to be considered for such renaming (in our example, files matching the pattern test*.txt)
Note:
I am not sure if there is a way for ‘rename’ to traverse sub-folders as well. However, the shell script option below handles this limitation.
Approach 2: Using a shell script
In case you don’t have the rename utility on your flavor of Linux/Unix, you can use this simple bash script:
#!/bin/bash for cur in $(find . -name 'test*.txt'); do new=`echo $cur | sed 's/test/blah/'` mv $cur $new done
The advantage here is that this will traverse the sub-folders as well (unlike rename).
- Anand
Category: How do I?