[Techtalk] bash/perl script to rename files...

Sean McAfee mcafee at transmeta.com
Fri Oct 26 14:34:56 EST 2001

Walt <pippin at fred.net> wrote:
>I need a perl script that replaces spaces
>in a filename with underscores...

>I'm sure that this can be achieved, I just
>don't know how to do it.

The Perl Cookbook has a pretty nifty "rename" script:


$op = shift or die "Usage: rename expr [files]\n";

chomp(@ARGV = <STDIN>) unless @ARGV;

for (@ARGV) {
    $was = $_;
    eval $op;
    die $@ if $@;
    rename($was, $_) unless $was eq $_;

The first argument to the script should be a Perl expression that will be
evaluated for every file named on the command line, or (if there are none)
every file on the standard input stream, one per line.  When the expression
is evaluated, $_ (the default variable) will contain a file name.  If
evaluating the expression changes $_, the file will be renamed to the new
value of $_.


Change spaces to underscores:
rename 's/ /_/g'
rename 'tr/ /_/'

Change .foo extensions to .bar:
rename 's/\.foo$/.bar/' *

Change .foo to .bar in an entire directory tree:
find . -type f | rename 's/\.foo$/.bar/'

Append a .bak extension to all .cc files:
rename '$_ .= ".bak" if /\.cc$/' *

"It's a deicide.  This guy Lokk arranged the murder of this guy Baldur.
 Now Baldur's Dad's going postal and threatening to end the universe..."
"I've had enough of this.  Listen, Pops, you end the universe and I'm
running you BOTH in!" -- from Top Ten #7 | Sean McAfee | mcafee at transmeta.com

More information about the Techtalk mailing list