Usually, the command "mv" is used for renaming single files or directories. Most Linux systems will include a rename command as well that can use wildcards to rename multiple files or directories.

This script is useful when you need to rename many files and can create a perl expression with the proper logic.

The script is available on the HEP Linux cluster at ~rockwell/local/bin/rename.pl The script was developed from an example in The Perl Cookbook.

Usage

rename.pl expr file [more files]

expr is a perl expression that will be executed using perl's eval function. You can manipulate $_ to change the name. (You can also implicitly work with $_.)

Examples

Have files 320 files named 0__.root to 319.root, rename these to 206.root to 525.root.

This will eliminate the _ characters:

rename.pl 's/_//g' *.root

This will do the renumbering:

rename.pl '/(\d+).root/; $num=$1+206; $_="$num.root"' *.root

These operations may be combined:

rename.pl 's/_//g; /(\d+).root/; $num=$1+206; $_="$num.root"' *.root

The script checks for filename clobbers and won't execute the command if it detects one. However, the logic isn't advanced and the script will fail on some cases that are possible to handle, for instance the case where a new name conflicts with an existing name, but the conflicting existing name is being changed in the same operation. For this case, rename the files to a temporary name and then to the final name (this functionality will be handle automatically in a future version of the script).

rename.pl 's/_//g; /(\d+).root/; $num=$1+206; $_="$num.root-XXX"' *.root
rename.pl 's/(.*)-XXX$/\1/' *.root-XXX

-- TomRockwell - 13 Oct 2005
Topic attachments
I Attachment Action Size Date Who Comment
rename.pl.txttxt rename.pl.txt manage 1.4 K 13 Oct 2005 - 15:13 TomRockwell rename.pl perl script
Topic revision: r4 - 16 Oct 2009, TomRockwell
 

This site is powered by FoswikiCopyright © by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding Foswiki? Send feedback