develooper Front page | perl.beginners | Postings from May 2006

Perl script to search and replace a string in a file

Thread Next
From:
Nishi Bhonsle
Date:
May 31, 2006 14:40
Subject:
Perl script to search and replace a string in a file
Message ID:
cd8ef3c10605311439j6a7b1ae6lf5bb600b7aa660a6@mail.gmail.com
Hi:

I have the following script that takes in an input file, output file and
replaces the string in the input file with some other string and writes out
the output file.
I want to change the script to traverse through a directory of files
ie instead of prompting for input and output files, the script should take
as argument a directory path such as C:\temp\allFilesTobeReplaced\ and
search for a string x and replace it with y for all files under that
directory path and write out the same files
perl C:\temp\allFilesTobeReplaced\

How do I do this?

Please help.
Thanks in advance.
--------------------------------------

$file=$ARGV[0];
open(INFO,$file);
@lines=<INFO>;
print @lines;
open(INFO,">c:/filelist.txt");
foreach $file (@lines)
{
#print "$file\n";
print INFO "$file";
}
#print "Input file name: ";
#chomp($infilename = <STDIN>);
if ($ARGV[0]){
 $file= $ARGV[0]
}
print "Output file name: ";
chomp($outfilename = <STDIN>);
print "Search string: ";
chomp($search = <STDIN>);
print "Replacement string: ";
chomp($replace = <STDIN>);
open(INFO,$file);
@lines=<INFO>;
open(OUT,">$outfilename") ||
    die "cannot create $outfilename: $!";
foreach $file (@lines)
 {    # read a line from file IN into $_
    s/$search/$replace/g; # change the lines
    print OUT $_; # print that line to file OUT
}
close(IN);
close(OUT);

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About