Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!


Click here to return to the 'Install the Linux rename utility' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
Install the Linux rename utility
Authored by: bimtob on Jul 12, '05 07:35:24PM
Here's one that I wrote that has fewer options, but I find it very useful. It accepts full perl regular expressions as arguments.
#!/usr/bin/perl
# remv: Regular Expression mv
# Usage: remv [-t | -r] filter "regular expression"
# -t is to test regex
# -r is to perform the mv operation
# filter is an argument to ls (ex. *.pl)
# regular expression is put in quotes. $s are backslash \escaped
#
# Example: remv -t \*.jpg "s/oldname(\d)(.jpg)/newname\$1\$2/"
#

$mode = shift;
$filter = shift;
$regex = shift;
$str = "\$file =~ $regex";
chomp($filter);
chomp($regex);

@filelist = `ls $filter`;

if ($mode eq "-r") {
	foreach $file (@filelist) {
		chomp($file);
		$oldname = $file;
		eval $str;
		print "renaming: $oldname to $file\n";
		`mv $oldname $file`;
	}
}
elsif ($mode eq "-t") {
	foreach $file (@filelist) {
		chomp($file);
		$oldname = $file;
		eval $str;
		print "$oldname -> $file\n";
	}
}
else { print "-t\ttest regex\n-r\trename files\n";}
So something like:
remv -t \*.jpg "s/oldname(\d)(.jpg)/newname\$1\$2/"
will rename "oldname1.jpg" and "oldname2.jpg" to "newname1.jpg" and "newname2.jpg" repectively.

[ Reply to This | # ]
Use this one...
Authored by: bimtob on Jul 12, '05 07:40:46PM
One more time. It ate my backslashes.

#!/usr/bin/perl
# remv: Regular Expression mv
# Usage: remv [-t | -r] filter "regular expression"
# -t is to test regex
# -r is to perform the mv operation
# filter is an argument to ls (ex. *.pl)
# regular expression is put in quotes. $s are backslash \escaped
#
# Example: remv -t \*.jpg "s/oldname(\d)(.jpg)/newname\$1\$2/"
#

$mode = shift;
$filter = shift;
$regex = shift;
$str = "\$file =~ $regex";
chomp($filter);
chomp($regex);

@filelist = `ls $filter`;

if ($mode eq "-r") {
	foreach $file (@filelist) {
		chomp($file);
		$oldname = $file;
		eval $str;
		print "renaming: $oldname to $file\n";
		`mv $oldname $file`;
	}
}
elsif ($mode eq "-t") {
	foreach $file (@filelist) {
		chomp($file);
		$oldname = $file;
		eval $str;
		print "$oldname -> $file\n";
	}
}
else { print "-t\ttest regex\n-r\trename files\n";}
[\code]


[ Reply to This | # ]
2nd correction
Authored by: bimtob on Jul 12, '05 08:06:23PM
The backslashes got eaten in the first comment. On the command line you should type the command like this:
rgxmv -t "*.jpg" "s/oldname(\d)(.jpg)/newname\$1\$2/"
and it will print:
oldname1.jpg -> newname1.jpg
oldname2.jpg -> newname2.jpg
then to actually rename the files use the "-r" switch instead of "-t"

[ Reply to This | # ]