2

I want to grep a word with line number. It's easily possible in the shell with the command grep -n or with sed. Is there any equivalent available in Perl? I have checked the grep function, however I am unable to find anything like I need.

daxim
  • 39,270
  • 4
  • 65
  • 132
Mandar Pande
  • 12,250
  • 16
  • 45
  • 72

1 Answers1

12

In a file called mygrep:

#!/usr/bin/perl

use strict;
use warnings;

my $match = shift;

while (<>) {
  if (/\Q$match/) {
    print "$. : $_";
  }
}

Then from the command line:

$ ./mygrep if mygrep 
6 : my $match = shift;
9 :   if (/\Q$match/) {

Should be enough to get you started.

Dave Cross
  • 68,119
  • 3
  • 51
  • 97
  • Hey It's good ! But what about multiple matches within multiple files...like `grep -n "word" *` or with `xargs` etc. Do i need to write a loop for each file after `ls`? – Mandar Pande Jun 14 '11 at 09:17
  • Like I said, it's enough to get you started :-) I think your other questions will be answered if you read the documentation for $. (in perldoc perlvar). – Dave Cross Jun 14 '11 at 10:06
  • 3
    Seems a bit excessive to write this as a script. You can do it easily as a one-liner: perl -wne 'print "$.: $_" if m/\Qmatch/' – William Pursell Jun 14 '11 at 14:05
  • 2
    @William Pursell - yes but @davorg has written something that someone just learning Perl will benefit from. – Nic Gibson Jun 14 '11 at 14:09
  • @William Pursell: Sure, but the program version is far easier to change to add the other bells and whistles that mandy asked for. – Dave Cross Jun 14 '11 at 16:33
  • @Nic Gibson Someone just learning perl will benefit greatly from learning -p/-n early on. – William Pursell Jun 14 '11 at 18:17
  • @mandy no, it already does that thanks to the magic of `while (<>)`. Although it doesn't tell you *which* file the match was in — to get that, you want to add `$ARGV` to the print line :) – hobbs Jun 14 '11 at 19:33
  • Working well for a single file for me. But doesn't glob. Is it supposed to work on ActiveState Perl on Windows? – Uri London Nov 08 '12 at 15:46