Thursday, June 5, 2008

Renaming multiple files on Linux

The syntax for the rename command is:

rename [ -v ] [ -n ] [ -f ] perlexpr [ files ]

-v : verbose

-n : test run

perlexpr: perl regular expression

Example 1: change "*.htm" to "*.html"

$ rename -n ’s/\.htm$/\.html/’ *.htm

s - substitute : s/old/new

$ - end of string. That is search for only '.htm', not '.html'


Example 2: change filenames that have the pattern ########.JPG (8 numbers and capital .JPG) to something like BeachPics_########.jpg

$ rename -n 's/(\d{8})\.JPG$/BeachPics_$1\.jpg/' *.JPG

00001111.JPG renamed as BeachPics_00001111.jpg
00001112.JPG renamed as BeachPics_00001112.jpg
00001113.JPG renamed as BeachPics_00001113.jpg

\d{8} : count 8 digits

(\d{8}) : Parenthesis is meant to save this as an argument for later use

$1 : insert the string from the first set of parenthesis - in this case the 8 digits

$ rename -n 's/\d{5}(\d{3})\.JPG$/BeachPics_$1\.jpg/' *.JPG
00000123.JPG renamed as BeachPics_123.jpg
00000124.JPG renamed as BeachPics_124.jpg
00000125.JPG renamed as BeachPics_125.jpg

Example 3: replace 'weight_' to 'ffn_wt_' in all the files

$ rename -n 's/weight_*/ffn_wt_/g' *.txt
weight_far.txt renamed as ffn_wt_far.txt
weight_near.txt renamed as ffn_wt_near.txt
weight_top.txt renamed as ffn_wt_top.txt

No comments: