Have you ever said "I need to rename every file by changing FOO to BAR"? Well (and I'm sure there's easier ways to do this), I finally figured it out. :-)
ls *FOO* | perl -MFile::Copy -ne 'chomp;(my $x = $_) =~ s/FOO/BAR/;mov +e($_,$x)'

Replies are listed 'Best First'.
Re: Renaming bunches of files
by Aristotle (Chancellor) on Aug 08, 2003 at 00:39 UTC
    How about saving a process and coping correctly with oddly named files?
    perl -MFile::Copy -e 'for(@ARGV){ $a=$_; s/FOO/BAR/; move($a,$_) }' *F +OO*

    Makeshifts last the longest.

      If there happen to be lots of files that match the wildcard file-spec, some shells won't be able to handle this sort of command line ("too many args").

      Of course, such shells won't handle "ls *FOO*" either, since the shell tries to populate the command line based on the file spec, before running "ls" (i.e. you are certainly correct that "ls" is redundant here).

      Sometimes, one must resort to things like "ls | grep FOO | ..."

        find -name '*FOO*' -maxdepth 1 -print0 | xargs -r0 perl -MFile::Copy - +e 'for(@ARGV){ $a=$_; s/FOO/BAR/; move($a,$_) }'
        (Or if you are appalled by the find syntax, it may suffice to
        ls | grep FOO | xargs -r perl -MFile::Copy -e 'for(@ARGV){ $a=$_; s/FO +O/BAR/; move($a,$_) }'
        though that won't cope with pathologically named files.)

        Makeshifts last the longest.

Re: Renaming bunches of files
by graff (Chancellor) on Aug 08, 2003 at 04:52 UTC
    If you really are just renaming, why not just use the "rename" function? (`perldoc -f rename`)
    ls *FOO* | perl -ne 'chomp; $o=$_; s/FOO/BAR/; rename $o,$_'
    (Does the "File::Copy::move()" function really do anything different from this?)
      graff,
      Yes. rename does not work across file systems (usually). Now while the original code is changing the name in place, using File::Copy instead of rename allows modifications to the location of the new file without breaking anything.

      Cheers - L~R

Re: Renaming bunches of files
by punkcraft (Pilgrim) on Aug 08, 2003 at 00:10 UTC
    If you prefer to run a script rather than remember and type all that in, there is one floating around. It was originally written by Larry himself. Tom Christiansen posted it to comp.lang.perl.misc a few years back.
      $ which rename /usr/bin/rename $ head -n 5 `which rename` #!/usr/bin/perl -w # # This script was developed by Robin Barker (Robin.Barker@npl.co.uk), # from Larry Wall's original script eg/rename from the perl source. #