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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Replacing word in file

Status
Not open for further replies.

bretttt

Programmer
Jul 23, 2002
74
US
I have read in a file to @file
i need to replace the word "cat" with word "dog".
Not literally lol

thanks.
 
open (INFILE, &quot;< cat.txt&quot;); # < = input
open (OUTFILE, &quot;> dog.txt&quot;); # > = output

while (<INFILE>) { # loop over the input 'cat.txt' file
print &quot;before: $_&quot;;
s/\bcat\b/dog/g; # substitute 'cat' with 'dog' (\b = word boundary)
print OUTFILE; # print this change to the 'dog.txt' outfile
print &quot; after: $_&quot;;
}

close OUTFILE;
close INFILE;


Kind Regards
Duncan
 
open (FILE, &quot;<file.txt&quot;);
flock (FILE, 2);
undef ($/);
$cont = <FILE>;
close FILE;
$cont =~ s/cat/dog/g; #include boudary if it's the case
open (FILE, &quot;>file.txt&quot;);
print FILE $cont;
flock (FILE, 8);
close FILE;

try this too

D.

Masochist: Windows programmer with a smile.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top