How to rename multiple files from the shell - tips and tricks
Renaming multiple files seems to be a problem which many newcomers to shell scripting, or administration, have problems with. But once you've done it a few times the actual solutions are very simple.
There are many cases where you might have a large number of files to rename en masse, for example files which are output from a given script or tool. Or files that must be renamed to be uploaded to a web-host.
How you rename the files mostly depends on which tools you have available, and which shell you're using.
One way to rename large numbers of files is using the looping facility within the bash shell.
For example, this one-liner renames multiple files adding a sequential number using the printf syntax:
# Rename files adding sequential number
NUM=1 ; for FILE in *.jpg ; do mv -v "$FILE" `printf "prefix-%03d-suffix.jpg" $NUM` ; NUM=`expr $NUM + 1` ; done
- 211 reads
Might be useful ...
Here's a Perl script I use for renaming files using regular expressions.
It outputs the mv command to stdout so you can check what's going to happen before you pipe its output to /bin/bash:
#!/usr/bin/perl
$options = "OPTIONS:\n\t-s: replace spaces with underscores\n\t-l: change all characters to lowercase\n\t-u: change all characters to uppercase\n";
unless( $ARGV[1]) {
die ("Usage: $0 \"string to match\" \"string to replace it with\"\nNote \"string to replace it with\" must consist of spaces exclusively if you wish to remove \"string to match\" \n$options");
};
use Getopt::Std;
getopt('');
$in = $ARGV[0];
$out = $ARGV[1];
if ($out =~ /^\s*$/) {
$out = "";
};
foreach $file (`ls`) {
chomp $file;
$filenew = $file;
# this construct allows you to use backreferences
my $regexp = "\$filenew =~ s/$in/$out/";
eval($regexp);
#get rid of trailing spaces we may have created just now
$filenew =~ s/^\s+//;
$filenew =~ s/\s+$//;
if ($opt_s) {
$filenew =~ s/\s+/_/g;
};
if ($opt_l) {
$filenew = lc($filenew);
};
if ($opt_u) {
$filenew = uc($filenew);
};
print "mv \"$file\" \"$filenew\"\n";
};
Thanks
Thanks Matthijs,
That looks like a very nice tool. I will definitely try it out. Thank you for your very nice site as well!
Priyadarshan
Post new comment