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

Perl script to search and replace a string in a file

Thread Next
Nishi Bhonsle
May 31, 2006 14:40
Perl script to search and replace a string in a file
Message ID:

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.

print @lines;
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(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

Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About