adir
adir

Reputation: 1287

How can i find a specific line in a file using Perl?

I am new to Perl. I want to find a string in some file and then i want the whole line which contains the string.

Upvotes: 5

Views: 7938

Answers (3)

MissFiona
MissFiona

Reputation: 129

if ( !open(LOGFILE, "<myfile.log") ) 
{
print "ERROR: failed to open myfile.log\n";}
else {   
while (<LOGFILE>){
if ($_ =~ /pattern/)
    {    print "found\n";
         break;
     }
}   
close (LOGFILE);
}

Upvotes: 2

Igor
Igor

Reputation: 27248

  1. Open the file

  2. Loop, while there are lines to read from the file

    2.1 Using regular expressions, check if the line matches the pattern: if ($line =~ /pattern/).

    2.2 If yes, print the string

  3. Close the file.

Upvotes: 9

JRFerguson
JRFerguson

Reputation: 7516

perl -ne 'print if m/whatever/' file

Upvotes: 11

Related Questions