4 # I wrote this to help me rename a group of mp3 files based on a list of
5 # tracks from a website.
7 # So, this script examines a newline-separated list of
8 # track names and renames the files in the current directory based on that.
10 # This could be improved in some ways. The parts specific to audio files
11 # should probably be optional. But it works for me, so I'll leave it alone for
21 if ($ARGV[0] eq "-f") {
25 #Make sure there are no non-mp3 files in the directory
27 `find -maxdepth 1 -noleaf | grep -v mp3\$ | grep -v ^.\$ `;
30 `find -maxdepth 1 -noleaf | grep -v flac\$ | grep -v ^.\$ `;
31 if ($non_flac_files) {
33 `find -maxdepth 1 -noleaf | grep -v wav\$ | grep -v ^.\$ `;
35 die "Non mp3 or flac or wav files or subdirectories found in this directory!";
40 #Get input from the user
42 my @input_lines = <STDIN>;
44 foreach my $line (@input_lines) {
48 die "can't use slashes in filenames";
51 $line =~ s/[\t ]*$//; # strip trailing whitespace
53 if ($mp3_to_flac == 1) {
54 $line =~ s/\.mp3$/\.flac/;
58 #Make sure this track title contains a number.
59 die "The name of this file does not contain a number."
60 unless ($line =~ '[0-9]');
61 #If the line has some non-whitespace component, add it to the list of
63 $line = TrimWhitespace($line);
64 push (@cooked_lines, $line);
65 #print "processing line..." . "\"" . $line . "\"\n"
69 #Make sure we have the right number of mp3s in this folder
70 my $files_in_folder = `find | grep -v ^.\$ | wc -l`;
71 chomp $files_in_folder;
72 my $number_of_input_lines = scalar(@input_lines);
73 if ($files_in_folder != $number_of_input_lines) {
74 die "$files_in_folder mp3s in the folder, but $number_of_input_lines input lines given!";
78 open(FIND_OUTPUT, "find . -maxdepth 1 | grep -v ^.\$ | sort -n | ");
81 while (defined($find_line = <FIND_OUTPUT>)) {
83 my $final_name = $input_lines[$i];
84 print "renaming \"$find_line\" to \"$final_name\"\n";
85 if (system("mv \"$find_line\" \"$final_name\"")) {
90 print "** rename complete **\n";
93 #Replace multiple whitespace characters with a single one
96 my $file_name = @_[0];
100 $old_file_name = $file_name;
101 $file_name =~ s#\s\s# #g;
102 } while ($file_name ne $old_file_name);