Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I change several files at the same time

Little tricks

How do I change several files at the same time

by  toolkit  Posted    (Edited  )
For example, you wish to recursively modify all HTML files. There are two approaches:

In UNIX you can use the following one-liner from the shell:

Code:
find docs -type f -name "*.html" | xargs perl -i -p -e 's/foo/bar/g'

Alternatively, you can use the File::Find package:

Code:
use File::Find;

sub change {

    if( -f && /\.html$/ ) {

        my $in  = $_;
        my $out = "$in.$$";

        open( IN, $in ) or die;
        open( OUT, ">$out" ) or die;

        while( <IN> ) {
            s/foo/bar/g;
            print OUT;
        }

        close IN;
        close OUT;

        rename( $out, $in );
    }
}

my @dirs = qw( docs );

find ( \&change, @dirs );

Happy coding, Cheers NEIL :)
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top