How to quickly find the first line of a file that matches a regular expression?

I want to find a line in a file using regex, inside a Perl script.

Assuming it is on a system with grep installed, it is better:

  • call external grepusing commandopen()
  • open()file directly and use the loop whileand if ($line =~ m/regex/)?
+5
source share
7 answers

In a modern Perl implementation, regexp should be as fast as grep, but if you are concerned about performance, why not just give it a try? In terms of code cleanliness and reliability, invoking an external command-line tool is definitely not very good.

+9

open.

my $regex = qr/blah/;
while (<>) {
  if (/$regex/) {
    print;
    exit;
  }
}
print "Not found\n";

, , , print $_, <> -, .

while (my $line = <>) {
  if ($line =~ /$regex/) {
    print $line;
    exit;
  }
}

.

: , , , .

+6

grep: Linux, LANG UTF-8 (, my - LANG = en_GB.UTF-8), grep, sed, sort , , 10 . , . grep:

LANG= LANGUAGE= /bin/grep

: , 100

+5

.

  • Perl, .
  • grep, , , Perl, .

, Perl, .

+3

. ,

$line = `grep '$regex' file | head -n 1`;

- , .

, , perl, , - .

+3
sed '/pattern/q' file
+2

script ( 10 ). Perl , . grep script, . , , Perl , grep. , , . : , .

+1

All Articles