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

Programming Wiki : PerlFindReplace

WikiHomePage :: Categories :: PageIndex :: RecentChanges :: RecentlyCommented :: Login/Register
Most recent edit on 2006-04-16 21:39:40 by ScottRippee

Additions:
open(FILE,$fileName); || die("Cannot Open File");

Deletions:
open(FILE,$fileName);



Edited on 2006-04-16 21:39:11 by ScottRippee

Deletions:
my @newfile;



Edited on 2006-04-16 21:38:42 by ScottRippee

Additions:
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.

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



Oldest known version of this page was edited on 2006-04-16 21:37:48 by ScottRippee []
Page view:

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];
my @newfile;

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

open(FILE,$fileName);
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 word replaced wtih bar.
Powered by Wikka Wakka Wiki 1.1.6.0
Page was generated in 0.0404 seconds