Exercise: Renaming Files En Masse

 <  Day Day Up  >  

This exercise will provide another (small) tool for your toolkit. This utility allows you to rename files given a directory name , a pattern to look for, and a pattern to change it to. For example, if a directory contains the filenames Chapter_01.rtf , Chapter_02.rtf , Chapter_04.rtf , and so on, you could rename all the files to Hour_01.rtf , Hour_02.rtf , Hour_04.rtf , and so on. This task normally isn't easy at a command prompt and just silly when you're using a GUI-based file browser.

Using your text editor, type the program from Listing 10.3 and save it as Renamer . If you can, be sure to make the program executable according to the instructions you learned in Hour 1.

When you're done, try running the program by typing the following at a command line:

  perl -w Renamer  

or, if you could make the program executable,

  Renamer  

Listing 10.4 shows some sample output from this program.

Listing 10.3. Complete Listing for Renamer
 1:   #!/usr/bin/perl -w 2: 3:   use strict; 4: 5:   my($dir, $oldpat, $newpat); 6:   print "Directory: "; 7:   chomp($dir=<STDIN>); 8:   print "Old pattern: "; 9:   chomp($oldpat=<STDIN>); 10:  print "New pattern: "; 11:  chomp($newpat=<STDIN>); 12: 13:  opendir(DH, $dir)  die "Cannot open $dir: $!"; 14:  my @files=readdir DH; 15:  close(DH); 16:  my $oldname; 17:  foreach(@files) { 18:      $oldname=$_; 19:      s/$oldpat/$newpat/; 20:      next if (-e "$dir/$_"); 21:      if (! rename "$dir/$oldname", "$dir/$_") { 22:              warn "Could not rename $oldname to $_: $!" 23:      } else { 24:              print "File $oldname renamed to $_\n"; 25:      } 26:  } 

Lines 13 “15 : The entries in the directory indicated by $dir are read into @files .

Lines 17 “19 : Each file from @files is assigned to $_ and that name is saved in $oldname . The original filename in $_ is then changed to the new name on line 19.

Line 20 : Before renaming the file, this line makes sure the target filename doesn't already exist. Otherwise, the program could rename a file into an existing name ”destroying the original data.

Lines 21 “25 : The file is renamed, and warnings are printed if the rename fails. Notice that the original directory name needs to be appended onto the filenames ”for example, $dir/$oldname ”because @files doesn't contain full pathnames, which you need for the rename.

Listing 10.4. Sample Output from Renamer
 1:  Directory:  /tmp  2:  Old Pattern:  Chapter  3:  New Pattern:  Hour  4:  File Chapter_02.rtf renamed to Hour_02.rtf 5:  File Chapter_10.rtf renamed to Hour_10.rtf 

 <  Day Day Up  >  


SAMS Teach Yourself Perl in 24 Hours
Sams Teach Yourself Perl in 24 Hours (3rd Edition)
ISBN: 0672327937
EAN: 2147483647
Year: 2005
Pages: 241

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net