in reply to Remove string from file

Here's an improved version of the code I posted in the CB in answer to your question.

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

Replies are listed 'Best First'.
Re^2: Remove string from file
by Anonymous Monk on Mar 13, 2007 at 11:49 UTC
    Hi Your solution seems to be great. But i have a different problem. I have a file 'A' which contains say n lines each having unique name. Now in another file 'B' I need to search for these n strings from 'A' and delete those lines in this 'B' and create a new file 'C'. Can any one help me on this
      Your post isn't going to attract much attention here at the bottom of an old thread. Could I suggest that you repost here with a more detailed version of your question (and what code you've got so far).

      --------------------------------------------------------------

      "If there is such a phenomenon as absolute evil, it consists in treating another human being as a thing."
      John Brunner, "The Shockwave Rider".