renaming batches of files in linux

I often need to rename many files at one time. Usually I just want to add an extension to the end of the name. The best way I have found is with the rename command. I have a few .rb files which I want to rename as .rb.erb files.

[code]
-rwxr-xr-x 1 philip philip 218 2010-10-22 17:19 message_broadcaster.rb
-rwxr-xr-x 1 philip philip 90 2010-10-22 17:19 message_group_criteria.rb
-rwxr-xr-x 1 philip philip 2180 2010-10-22 17:19 message.rb
-rwxr-xr-x 1 philip philip 193 2010-10-22 17:19 message_recipient_group.rb
-rwxr-xr-x 1 philip philip 134 2010-10-22 17:19 message_recipient.rb
-rwxr-xr-x 1 philip philip 427 2010-10-22 17:19 message_template_owner.rb
-rwxr-xr-x 1 philip philip 661 2010-10-22 17:19 message_template.rb
[/code]

Running the rename command with a -n will show you files that will be changed without actually running the command. Let’s take a look at potential changes:
[code]rename -v -n ‘s/^([a-z_A-Z]+\.rb)$/$1.erb/’ *.rb[/code]
[code]
message_broadcaster.rb renamed as message_broadcaster.rb.erb
message_group_criteria.rb renamed as message_group_criteria.rb.erb
message.rb renamed as message.rb.erb
message_recipient_group.rb renamed as message_recipient_group.rb.erb
message_recipient.rb renamed as message_recipient.rb.erb
message_template_owner.rb renamed as message_template_owner.rb.erb
message_template.rb renamed as message_template.rb.erb
[/code]

Now we just take the -n off of the command and rerun it. Now we can relist the files and see the changes:
[code]ls -al[/code]
[code]
-rwxr-xr-x 1 philip philip 218 2010-10-22 17:19 message_broadcaster.rb.erb
-rwxr-xr-x 1 philip philip 90 2010-10-22 17:19 message_group_criteria.rb.erb
-rwxr-xr-x 1 philip philip 2180 2010-10-22 17:19 message.rb.erb
-rwxr-xr-x 1 philip philip 193 2010-10-22 17:19 message_recipient_group.rb.erb
-rwxr-xr-x 1 philip philip 134 2010-10-22 17:19 message_recipient.rb.erb
-rwxr-xr-x 1 philip philip 427 2010-10-22 17:19 message_template_owner.rb.erb
-rwxr-xr-x 1 philip philip 661 2010-10-22 17:19 message_template.rb.erb
[/code]

Easy.

Leave a Reply

Your email address will not be published. Required fields are marked *