#!/usr/local/bin/perl
#
#    Copyright (C) 1991 by Lutz Prechelt, Karlsruhe
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 1, or (at your option)
#    any later version.
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    If you don't have a copy of the GNU General Public License write to
#    Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

# Version:     1
# Author:      Lutz Prechelt (prechelt@ira.uka.de), 30.07.91
# Last Change: Lutz Prechelt, 30.07.91
#
# Usage: see message at "die" below.
# 
# Ideas: perhaps it's better to give the complete s/pat/newpat/ command
#        as a parameter, because that is more flexible (for instance to
#        use options g,i,e with s///, or different delimiters

if ($#ARGV < 2) {
  die "
   Usage: rename from_pattern to_pattern filename...

      Renames all of the files matching the from_pattern by replacing
      the from_pattern with the to_pattern in their names.
      Other files' names are unchanged. Filenames must not contain '!'
      The patterns are Perl regular expressions and are used in a single
        s/from/to/ command (so the \\1 syntax can be used).
        
    Examples:
      rename '.c' '.cr' *
          renames all files with names ending in '.c' to have ending '.cr'
      rename '^tryit([1-9]).([cp])*' 'dunnit\\1.\\2' *
          renames all files with names tryit<anydigit>.c or tryit<anydigit>.p
          to have first namepart 'dunnit' and same digit and suffix.
      (and, of course, there are always many other ways to say the same)
   exiting ";
}

$from = $ARGV[0];   # pattern to match
$to   = $ARGV[1];   # pattern to replace it with
shift; shift;

while ($#ARGV >= 0) {
  $oldname = $ARGV[0];
  $newname = $oldname;
  $prog = "\$check = (\$newname =~ s!" . $from . "!" . $to . "!)";
  eval ($prog);        # try to translate old name into new name
  if ($check >= 1) {   # translation successful
    printf ("%30s --> %s\n", $oldname, $newname);
    system ("mv -i $oldname $newname");  # ask before overwriting something
  }
  else {
    printf ("`%s` did not match pattern\n", $oldname);
  }  
  shift;
} 

exit 0;



