Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

rename files using regex.

by djbiv (Scribe)
on Jul 23, 2003 at 14:43 UTC ( #277174=snippet: print w/replies, xml ) Need Help??
Description: Ok, this is 'stolen' from the 'Perl Cookbook', and I would bet most veteran Monks will probably find this trivial but I enjoy it, and wanted to share it anyways.
whoops won't run with strict; (Oddly enough the example in the perl cookbook isn't using strict!), so I updated the code declaring $op and $was...
#!/usr/bin/perl -w
# rename - larry's filename fixer
# small script from the "perl cookbook"
# examples:     % rename 's/\.orig$//' *.orig
#         % rename 'tr/A-Z/a-Z/ unless /^Make/' *
#         % rename '$_ .= "bad"' *.f
#         % rename 'print "$_: "; s/foo/bar/ if <STDIN> =~ /^y/i' *
#         % find /tmp -name '*~' -print | rename 's/^(.+)~$/.#$1/'
use strict;

my $op = shift or die "Usage: rename expr [files]\n";
chomp(@ARGV = <STDIN>) unless @ARGV;    
for (@ARGV) {                                         
   my $was = $_;   
   eval $op;
   die $@ if $@;
   rename($was,$_) unless $was eq $_;               
Replies are listed 'Best First'.
(jeffa) Re: rename files using regex.
by jeffa (Bishop) on Jul 23, 2003 at 15:21 UTC
    Looks cool to me. The only recommendation i have sounds trivial at first, but if you get into the habit of using POD for your documentation now, you won't regret it. Here is some POD for your script, just append this to the end and modify to suite your needs:
    __END__ =head1 NAME rename - larry's filename fixer =head1 SYNOPSIS % rename 's/\.orig$//' *.orig % rename 'tr/A-Z/a-Z/ unless /^Make/' * % rename '$_ .= "bad"' *.f % rename 'print "$_: "; s/foo/bar/ if <STDIN> =~ /^y/i' * % find /tmp -name '*~' -print | rename 's/^(.+)~$/.#$1/' =head1 DESCRIPTION B<rename> is small script inspired from the "perl cookbook" that allows you to pass it a regular expression and filenames to apply that regex to. This is available online at =head1 AUTHOR djbiv
    Now you just type perldoc rename and voila! Instant documentation. This even works if the script is not in your current directory as long it is in a directory that is in your PATH. Check out POD in 5 minutes for more on POD, and definitely take a gander at The Dynamic Duo --or-- Holy Getopt::Long, Pod::UsageMan!. Very useful stuff. :)


    (the triplet paradiddle with high-hat)
Re: rename files using regex.
by bsb (Priest) on Jul 24, 2003 at 04:54 UTC
    I tried using rename to clean up file names but my expression outgrew the command line (not to mention the difficulty of escaping everything). I ended up hacking /usr/bin/rename.

    Here it is, for what it's worth:

    #!/usr/bin/perl -s # bsb hacked version of /usr/bin/rename use strict; use vars qw($q $n $t); use Convert::Translit; # Quiet, do Nothing, Test $q=$q; $n=$n; $t=$t; my $trans = Convert::Translit->new('Latin1' => 'ascii'); if ($t) { $n=1; @ARGV = <DATA>; } if (!@ARGV) { print "reading filenames from STDIN\n" unless $q; @ARGV = <STDIN>; chop(@ARGV); } for (@ARGV) { my $was = $_; $_ = $trans->transliterate($_); $_=lc; s/&/ and /g; s/\+/ plus /g; s/'//g; y/()~/---/s; print if $t; s/(?:(\.)|(-)|[\W_])+/$1||$2||'_'/ge; s/^[._-]//; s/[._-]$//; die $@ if $@; if( $was eq $_ ) { } # ignore quietly elsif( -e $_ ) { warn "$was not renamed: $_ already exists\n +"; } elsif($n || rename($was,$_)) { print "$was renamed as $_\n" unless + $q; } else { warn "Can't rename $was $_: $!\n"; } }

      Thanks bsb for pointing out the Convert::Translit::transliterate(). Now, only if the first locale could be guessed given some text...

Re: rename files using regex.
by Abigail-II (Bishop) on Jul 23, 2003 at 15:11 UTC
    Why would it have to use strict? Larry's well known rename program predates Perl5, so I wouldn't expect it to use strict. Besides, the code is Larry's, and AFAIK, Larry hardly ever uses strict. And neither does Damian for that matter. (Conspiricy?)

    There's little value in adding 'use strict' to old programs. Strictness is mostly a development aid.


      Strictness is mostly a development aid.

      I'm going to disagree with that statement. Strictness is both a development aid and a debugging aid. For example, I am attempting to maintain some crappy code that is in production that was originally written by C programmers who don't understand references. By adding strict, I can detect and fail on attempts to use non-references as references. While testing should catch these, it won't catch them all.

      Personally, I feel that if you're maintaining and updating an old program, it should be made strict. (Preferably, I'd add warnings to it, as well, but that's truly a personal preference. I'm anal. *grins*)

      We are the carpenters and bricklayers of the Information Age.

      Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

      Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.

      good notes! I enjoyed your comment, and didn't even think about the snippet pre-dating strict;
Re: rename files using a GUI?
by bsb (Priest) on Jul 24, 2003 at 09:00 UTC
      That's a good example of why literature is written in text, and only first graders at most "read" picture books.

      Makeshifts last the longest.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://277174]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (2)
As of 2017-08-18 03:55 GMT
Find Nodes?
    Voting Booth?
    Who is your favorite scientist and why?

    Results (294 votes). Check out past polls.