Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of “grep -n” in Perl?

Tags:

perl

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.

like image 391
Mandar Pande Avatar asked Nov 18 '25 14:11

Mandar Pande


1 Answers

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.

like image 92
Dave Cross Avatar answered Nov 20 '25 11:11

Dave Cross



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!