Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Perl script to find particular string and save those lines in another file?

by sumathigokul (Acolyte)
on May 05, 2015 at 05:13 UTC ( [id://1125666]=perlquestion: print w/replies, xml ) Need Help??

sumathigokul has asked for the wisdom of the Perl Monks concerning the following question:

Hi all, i want to search in a text file for '2' and copy the whole statement in another text file. Here is the code. It prints those matched statements and it also generated new.txt file, but the file is empty.

use strict; my $find = "2"; open (FILE, "<high_fanout.txt") or die "could not open:$!"; my @line = <FILE>; for (@line) { if ($_ =~ /$find/) { print "$_\n"; print NEW "@line\n"; } } open (NEW, ">new.txt" ) or die "could not open:$!"; close (FILE); close (NEW);

can anyone help me out from this mistake? Thank you all.

  • Comment on Perl script to find particular string and save those lines in another file?
  • Download Code

Replies are listed 'Best First'.
Re: Perl script to find particular string and save those lines in another file?
by graff (Chancellor) on May 05, 2015 at 05:24 UTC
    You seem to be opening the "NEW" file handle after you've been trying to write to it. Trying opening "NEW" before the "for" loop.

    (Also, it's better to do it like this:

    use strict; my $find = "2"; open( NEW, ">", "new.txt" ) or die "..." open( FILE, "<", "high_fanout.txt") or die "..." while (<FILE>) { print NEW if ( /$find/ ); }
    (updated to "use strict" and add "my" for the one variable)

      Thank you, this code works.

      use strict; my $find = "2"; open (NEW, ">", "new.txt" ) or die "could not open:$!"; open (FILE, "<", "high_fanout.txt") or die "could not open:$!"; while (<FILE>) { print NEW if (/$find/); } close (FILE); close (NEW);
Re: Perl script to find particular string and save those lines in another file?
by aaron_baugher (Curate) on May 05, 2015 at 05:39 UTC

    You need to open the output file before you write to it. Move the "open (NEW" line up above the loop that prints to it.

    Aaron B.
    Available for small or large Perl jobs and *nix system administration; see my home node.

Re: Perl script to find particular string and save those lines in another file?
by hdb (Monsignor) on May 05, 2015 at 05:25 UTC

    You have to open your NEW file before you print into it.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1125666]
Approved by graff
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (2)
As of 2024-04-24 14:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found