[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: how to rename multiple files



On Mon, Dec 09, 2002 at 11:33:03PM -0800, Osamu Aoki scribbled...
> On Mon, Dec 09, 2002 at 10:02:25PM -0600, Shyamal Prasad wrote:
> >     "drew" == drew cohan <debian@drewcohan.com> writes:
> > 
> >     drew> How do I rename all files in a directory matching the
> >     drew> pattern *.JPG to *.jpg in a bash shell script?  Thanks to
> >     drew> you guys I can check for the existence of jpgs in a
> >     drew> directory, but can't seem get 'mv' to rename them for me
> >     drew> (always complains that the last argument must be a
> >     drew> directory).
> > 
> > Still another way:
> > 
> > for i in *.JPG
> > do
> >   mv $i `basename $i .JPG`.jpg
> > done
> 
> Simplest alternative without sub-shell nor special command:
> 
> for i in *.JPG
> do
>   mv $i ${i%\.JPG}.jpg
> done
> 
My way:

<perl.mmv>
#!/usr/bin/perl -w
################################################################################
#                                      mmv
#     Renames files based on regex patterns.
################################################################################
use Getopt::Std;
getopts("tv");

die "bad usage\n" unless (@ARGV > 2);
my ($p1, $p2) = @ARGV;

$opt_t = 1 if defined $opt_t;
$opt_v = 1 if defined $opt_v;

my $newFile;
foreach my $file (@ARGV)
{
  if ($file =~ m#$p1#)
  {
    $newFile = $file;
    $newFile =~ s/$p1/$p2/;

    print "Move '$file' to '$newFile'\n" if ($opt_t or $opt_v);
    rename $file, $newFile unless ($opt_t);
  }
}



Reply to: