Monday, February 16, 2009

Rename Multiple Files With Perl

So here's the problem: I have a directory full of files that have special characters. In this particular case they were spaces and pounds. So of course, for some reason I can't find a working way to do a quick bash script. I was trying to do a for x in `ls` ; do ... but because of the special characters my filenames weren't being read properly. Wonderful!

So, after maybe a good 20 minutes of trying to find the right shell commands to use, I gave up and wrote this quick perl script.

So...anybody wanna give me a hint on how I'd be able to do this in a shell script?


#!/bin/perl
#
$dir="/home/drin/tmp/";
opendir(DIR, $dir) || die "Couldn't open $dir";
@files = grep {/.doc/ && -f "$dir/$_"} readdir(DIR);
closedir(DIR);

for $x (@files) {
$y = $x;
$y =~ s/\#//g;
$y =~ s/\ /_/g;
print "Renaming $x to $y\n";
rename ($x, $y);
}


Cheers!

No comments: