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


In reply to Re: Remove string from file by g0n
in thread Remove string from file by bran4ever

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.