I originally made this script to remove white space from my files and directories names,
then I edited it a bit to rename files based on a pattern and replacement string.
I am still a beginner, so any comments would be appreciated.
(Sorry for my bad English.)

#!/usr/bin/perl =head1 Usage: rename-script [OPTIONS] PATH Options: -p Pattern to look for in file's name. Default '\s' -r Replacement string. Default '_' -n Don't use 'g' option modifier with pattern matching =cut use strict; use File::Spec; use File::Basename; use File::Find; use Getopt::Std; my %opts; getopts('np:r:', \%opts); my $path = shift @ARGV // die "need path argument.\n"; my $pat = $opts{p} // '\s'; my $rep = $opts{r} // '_'; my @found; die "bad pattern $pat\n" unless eval { "" =~ /$pat/; 1; }; find sub { unshift @found, $File::Find::name }, $path; for ( @found ) { my ($base,$dir) = (basename($_),dirname($_)); my $newbase; defined $opts{n} ? (($newbase = $base) =~ s/$pat/$rep/ ) : (($newbas +e = $base) =~ s/$pat/$rep/g ); if ( $newbase ne $base ) { my $newname = File::Spec->catfile($dir,$newbase); (-e $newname) and (warn("can't rename $_ to $newname: $newname alr +eady exists\n"),next) ; rename($_,$newname) or warn "can't rename $_ to $newname:$!\n"; } }

In reply to Recursive renaming script by amr noman

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.