9.9. Renaming FilesProblemYou have a lot of files whose names you want to change. Solution
Use a foreach $file (@NAMES) { my $newname = $file; # change $newname rename($file, $newname) or warn "Couldn't rename $file to $newname: $!\n"; } Discussion
This is straightforward.
A small change turns this into a generic Example 9.5: rename#!/usr/bin/perl -w # rename - Larry's filename fixer $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 $_; }
This script's first argument is Perl code that alters the filename (stored in Here are five examples of calling the rename program from your shell: % rename 's/\.orig$//' *.orig % rename 'tr/A-Z/a-z/ unless /^Make/' * % rename '$_ .= ".bad"' *.f % rename 'print "$_: "; s/foo/bar/ if <STDIN> =~ /^y/i' * % find /tmp -name '*~' -print | rename 's/^(.+)~$/.#$1/'
The first shell command removes a trailing
The second converts uppercase to lowercase. Because a translation is used rather than the % rename 'use locale; $_ = lc($_) unless /^Make/' *
The third appends
The fourth prompts the user for the change. Each file's name is printed to standard output and a response is read from standard input. If the user types something starting with a
The fifth uses
find
to locate files in
The
rename
script exemplifies the powerful Unix tool-and-filter philosophy. Even though we could have created a dedicated command to do the lowercase conversion, it's nearly as easy to write a flexible, reusable tool by embedding an See Also
The |
|