Fixed a bug when renaming files at the actual dir.
[anime_rename.git] / anime_rename
blob3ece3597a79a2b3e2e80813adbc33400d85b51ea
1 #!/bin/env perl
2 # anime_rename: A script to rename arbitrary anime chapters (it can rename any
3 #               kind of files of course, but that is the reason why i code it)
5 use warnings;
6 use Getopt::Long;
8 our %options;
10 $options{'-h --help'}= "Shows help and exit.";
11 $options{'-p --prefix'}="Sets the prefix of each file.";
12 $options{'-d --debug'}="Show debug information.";
13 $options{'-s --simulate'}="Do nothing just print what it will do (implies -d)";
15 sub
16 debug_eval
18   my $string = join '', @_;
19   print "$string" if $debug_eval;
20   eval "$string" unless $simulate;
23 sub
24 show_help
26   my ($option, $description, $format_top);
28   $format_top="format STDERR_TOP =\n"
29     . "$0 ". 
30     join(' | ', map {s/^[[:space:]]*([^[:space:]]+).*$/$1/g;$_} keys %options) 
31     . " <files to rename>"."\n"
32     . ".\n";
34   eval "$format_top";
36 format STDERR =
37 ~~^<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
38   $option,          $description
41   write STDERR while ( ($option, $description ) = each  %options);
42   exit 1
45 #####################################################################
46 # MAIN                                                              #
47 #####################################################################
49 our ($debug_eval, $simulate);
51 my $prefix;
53 GetOptions ( "help|h" => \&show_help
54     , 'prefix|p=s'=>\$prefix
55     , 'debug|d' => \$debug_eval
56     , 'simulate|s' => sub{ ($simulate,$debug_eval)=(1,1)}
57     );
59 unless (@ARGV)
61   print STDERR "$0 needs an argument!\n"
62     . "$0 --help for usage\n"
63     ;
65   exit 1
68 die "ERROR: I need a -p option (see $0 -h for usage)\n" unless $prefix;
70 foreach my $file (@ARGV)
72   my ($basedir, $numeric_id, $extension) =
73   ( $file =~ m|^(.*/)?[^[:digit:]]*\W?([[:digit:]]{2})\W?.*\.(.*)$|);
75   $basedir = './' unless $basedir;
76   $numeric_id = '' unless $numeric_id;
77   $extension = '' unless $extension;
79   debug_eval "rename '$file', '$basedir${prefix}_${numeric_id}.$extension'\n" 
80     if $basedir or $numeric_id or $extension;