Programming Wiki: Perl: Find and replace all occurances of one string with another

Programming Wiki : PerlFindReplace

WikiHomePage :: Categories :: PageIndex :: RecentChanges :: RecentlyCommented :: Login/Register

Perl: Find and replace all occurances of one string with another

Perl


usage:

findreplace.pl filename.txt "string to find" "replace with this"

findreplace.pl
#!/usr/bin/env perl                                                                                             

my $fileName=$ARGV[0];
my $searchStr=$ARGV[1];
my $replaceStr=$ARGV[2];

print ("\nFilename:",$fileName,"\n");
print ("Search String:",$searchStr,"\n");
print ("Replace String:",$replaceStr,"\n\n");

open(FILE,$fileName); || die("Cannot Open File");
my(@fcont) = <FILE>;
close FILE;

open(FOUT,">$fileName") || die("Cannot Open File");
foreach $line (@fcont) {
    $line =~ s/$searchStr/$replaceStr/g;
    print FOUT $line;
}
close FOUT;



Combined with find you can do a find and replace on all files in a directory and subdirectories
find . -type f -exec findreplace.pl {} "foo" "bar" \;

This would cause every file in the current directory and subdirectories of the current directory that contained the word foo to have that replaced wtih the word bar.

There are no comments on this page. [Add comment]

Powered by Wikka Wakka Wiki 1.1.6.0
Page was generated in 0.0177 seconds