< 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 Renamer1: #!/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: }
Listing 10.4. Sample Output from Renamer1: 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 > |