Renaming multiple files en masse?

Jeremy Prior jez at netcraft.com
Wed Apr 12 10:08:21 BST 2000


--h31gzZEtNLTqOjlF
Content-Type: text/plain; charset=us-ascii

# These shell loops are all well and good for quick hacks, but for real
# finesse, you need to do the job properly - ie perl! :-)
# 
# I've attached `move' - a program that allows you to apply perl
# expressions to filenames.
# 
# Just put it somewhere in you path, (optionally) create a link to `copy'
# (for the equivalent cp behaviour), and then the above would simply be.
# 
#   % move chop *.html
# 
# Although it's 50 lines long, only 38 are actual code, and 17 of those
# are the usage message!
# 
# Apart from a (possibly gratuitously and unnecessary) upgrade to
# perl5, this script has served me well for nearly 10 years...

Ahem - here's the script!

jez
--
Jeremy Prior  <jez at netcraft.co.uk>  http://www.netcraft.co.uk/
 Netcraft Ltd,  1 Somerset Street,  Bath,  BA1 1TS,  England.
  Tel: +44-1225-404405 (direct-dial)   Fax: +44-1225-404401

--h31gzZEtNLTqOjlF
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment; filename=move

#!/usr/local/bin/perl -ws
# move/copy - regexp mv/cp script
# 24/11/90 jez	Added -f option to override -i
# 07/02/91 jez	Added default options and egs from lwall's rename
# Based on original idea from Larry Wall 1990
# $Id: move,v 1.5 1998/06/09 10:27:06 jez Exp $

use strict;
use vars qw($prg $cmd $h $v $f $D);
($prg = $0) =~ s!.*/!!;		# basename()

($cmd = $prg) =~ tr/aeiouy//d;	# move -> mv, copy -> cp

my $usage = <<_EOU_;
$prg: '$cmd' with perl pattern matching
usage: $prg [-f][-D][-v][-h] '<perl command(s)>' file(s)
flags: -f = force (override interactive), -D = debug, -v = verbose, -h = help
examples:
  $prg 's/\.flip\$/.flop/' *		- *.flip to *.flop
  $prg s/flip/flop/ *			- *flip* to *flop*
  $prg 's/\.orig\$//' *.orig		- remove .orig from filenames
  $prg 's/\$/.orig/' */*.[ch]		- add .orig to your source files in *
  $prg 'y/A-Z/a-z/' *			- lowercase all filenames in .
  $prg 'y/A-Z/a-z/ unless /^Make/' *	- same except not Make* 
  $prg 'y/A-Z/a-z/ if -B' *		- same, but just binaries!
  $prg chop *~				- restore all ~ backup files
  $prg '\$_ .= ".bad"' *.f		- append .bad to filename
  $prg 'print "\$_: "; s/foo/bar/ if <stdin> =~ /^y/i' *
					- query-replace foo with bar
_EOU_

die $usage if defined $h;
my $DEBUG = defined $D;
my $VERBOSE = $v || $DEBUG;
my $flag = defined $f ? "-f" : "-i";

my $op = shift or die $usage;
die "$prg: must supply filename\n" unless @ARGV;

my $was;
for (@ARGV) {
    $was = $_;
    die "$prg: $was does not exist\n" unless -e $was;
    eval $op;
    die $@ if $@;
    if ($was ne $_) {
        print "$cmd $flag $was $_\n" if $VERBOSE;
        system $cmd, $flag, $was, $_ unless $DEBUG;
    }
}

--h31gzZEtNLTqOjlF--




More information about the Ukfreebsd mailing list