my $replacestring = "TOM"; open(my $infile,"<","inputfile.txt") or die $!; open (my $outfile,">","outputfile.txt") or die $!; while (<$infile>) { $_=~s/$replacestring//g; print $outfile $_; } close $infile; close $outfile;
That will read the content of 'inputfile.txt', and write out the content to 'outputfile.txt', removing $replacestring along the way. The key bit is $_=~s/$replacestring//g - that replaces any instance of $replacestring in the $_ variable with blank.
The remaining step is to rename 'inputfile.txt' as something else, and rename 'outputfile.txt' as 'inputfile.txt'.
Update: Something else you might want to look at: your post says that you want to remove a string, but later you say a line. This code removes the entire line - I'll let you work out why ;-)
my $string = "TOM"; open(my $infile,"<","inputfile.txt") or die $!; open (my $outfile,">","outputfile.txt") or die $!; while (<$infile>) { if ($_ !~/$string/) { print $outfile $_; } } close $infile; close $outfile;
--------------------------------------------------------------
"If there is such a phenomenon as absolute evil, it consists in treating another human being as a thing."
John Brunner, "The Shockwave Rider".
Can you spare 2 minutes to help with my research? If so, please click here
In reply to Re: Remove string from file
by g0n
in thread Remove string from file
by bran4ever
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |