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

How can I search for a string in a file?

Status
Not open for further replies.

Sina

Technical User
Jan 2, 2001
309
CA
Hello everyone,

How can I search a very large file, line by line for a string and if found print the entire line to another file.

Here is what I have, but it does not work very well for some reason.

Could you help.

I have a text file that looks like this.
202.142.152.20 some text some text and more and more
202.142.152.20 some text some text and more and more
202.142.152.20 some text some text and more and more202.142.152.20 some text some text and more and more202.142.152.20 some text some text and more and more
202.142.152.20 some text some text and more and more202.142.152.20 some text some text and more and more
202.142.152.20 some text some text and more and more202.142.152.20 some text some text and more and more

any time I find a string with this ip address 202.142.152.20 I would like to print the entire line to another file.

#!/usr/bin/perl
open (INFILE, &quot;< log_arc&quot;) or die &quot;can not open file&quot;;
open (MYOUT, &quot;> xresult.txt&quot; ) or die &quot;can not open file&quot;;

close MYOUT;
open (MYOUT, &quot;>> xresult.txt&quot; ) or die &quot;can not open file&quot;;

while(<INFILE>)
{
# detect the domain controller.
if ( /202.142.152.20/)
{
chomp $_;

print MYOUT &quot;$_ \n&quot;;
}

}

is this correct.

Thank you

 
Too many &quot;MYOUT&quot; statements. Use this:

Code:
open (INFILE, &quot;<log_arc &quot;) or die &quot;can not open file&quot;;
open (MYOUT, &quot;>> xresult.txt&quot; ) or die &quot;can not open file&quot;;
while(<INFILE>) {
            # detect the domain controller.
            if ( /202.142.152.20/)
            {
                chomp $_;

                print  MYOUT &quot;$_ \n&quot;;
                }

  }
close (MYOUT);
close (INFILE);
 
But the file is too big,

I would rather process it line by line./

Any idea?

 
This works:-

open (INFILE, &quot;<log_arc&quot;) or die &quot;can not open file&quot;;

open (MYOUT, &quot;>xresult.txt&quot;) or die &quot;can not create file&quot;;

while(<INFILE>) {
if (/202.142.152.20/) { # detect the domain controller.
chomp;
print MYOUT &quot;$_\n&quot;;
}
}

close INFILE;
close MYOUT;


I edited some lines of the loc_arc file to have lines that would NOT match

Kind regards
Duncan
 
The way that you have written the program already reads and processes the file line by line. You have done it correctly.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top