#!/usr/bin/perl -w # Emacs file vars -*- mode:cperl; tab-width:4; indent-tabs-mode:nil -*- # # filename: renx3.pl - Larry Wall's filename fixer # author: Eric Pement # date: 2004-09-24 # modified: 2005-08-15, 2012-01-06 # revised: 2012-08-31 to work under Cygwin # # Originally written by Larry Wall. Basic script in Tom Christiansen and # Nathan Torkington, "Perl Cookbook" (1998), p. 327, to rename files. # I expanded it to work on a DOS/Windows filesystem, and to support quiet # and verbose option switches, and totals of files changed. -- ENP. # use strict; use warnings; use Getopt::Std; sub show_help { my $s0 = $0; $s0 =~ s|^.*/||; # delete to last slash print <<"END_OF_HELP"; $s0 - Perl file renamer, version $VERSION Usage: $s0 [-options] 'perl expression' [afn1 afn2 ... ] Options: -n Do nothing. Don't rename, but show results of proposed action. -q Quiet mode. Do not display any results to the console. -v Verbose. Display renaming prompt and command-line arguments. Default action: Display "renaming OldName -> NewName" and total number of files renamed. END_OF_HELP } # main my $VERSION = '1.0'; our($opt_n,$opt_q,$opt_v); getopts('nqv'); # Foreach character X in the set (nqv), set $opt_X to 1. # -n = Do nothing. Don't rename, but show results of proposed action. # -q = Quiet mode. Do not display any results to the console. # -v = Verbose. Display renaming prompt and command-line arguments. # default = display "renaming OldName -> NewName" and total files renamed. my $op = shift or ( show_help(), exit ); # pattern or operation is required print "Verbose output:\n" if $opt_v; print " \$op is [$op]\n" if $opt_v; # If no filenames on the command tail, get them from stdin chomp(@ARGV = ) unless @ARGV; my @filelist = @ARGV; # remove duplicate files from filelist my %uniquefiles = (); foreach my $file (@filelist) { $uniquefiles{$file}++; } # revise @filelist to contain only unique, valid filenames my @uniqfilz = sort keys %uniquefiles; print " \@ARGV is [@ARGV]\n" if $opt_v; print " \@filelist is [@filelist]\n" if $opt_v; print " \@uniqfilz is [@uniqfilz]\n\n" if $opt_v; # get the longest filename: my $longest = 0; for (@uniqfilz) { $longest = length($_) if length($_) > $longest; } # Rename the files, printing the changes unless quelled by -q # or unless modified by -n my $sum = 0; for (@uniqfilz) { my $was = $_; eval $op; die $@ if $@; unless ($was eq $_) { printf("renaming %-*s -> %s\n", $longest, $was, $_) unless $opt_q; rename($was,$_) unless $opt_n; $sum++; } } print "Total of $sum file" . ($sum==1 ? "" : "s") . ($opt_n ? " would be" : "" ) . " renamed.\n" unless $opt_q; print "No files were renamed.\n" if $opt_n; #---end of script---