2011-06-14 71 views
2

我想用行号grep一个单词。使用命令grep -n或使用sed命令很容易。 Perl中是否有任何等价物?我检查了grep函数,但是我无法找到任何需要的东西。Perl中“grep -n”的等效含义是什么?

+0

我想这里是你需要:http://stackoverflow.com/questions/1849329/is-there-a-perl-shortcut-to-count-the-number-of-matches-in-a-string – 2011-06-14 08:18:42

+0

不,匹配数量与比赛的线数不同。 – 2011-06-14 08:39:19

回答

12

在一个名为mygrep文件:

#!/usr/bin/perl 

use strict; 
use warnings; 

my $match = shift; 

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

然后:

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

应该足以让你开始。

+0

嘿,这很好!但是,多个文件中的多个匹配怎么样...像'grep -n“word”*'还是'xargs'等。我需要在'ls'之后为每个文件编写一个循环吗? – 2011-06-14 09:17:56

+0

就像我说的,这足以让你开始:-)如果你阅读$的文档,我认为你的其他问题将得到解答。 (perldoc perlvar)。 – 2011-06-14 10:06:11

+3

似乎有点过分,将其作为脚本编写。你可以轻松地做到这一点:perl -wne'print'$:$ _“if m/\ Qmatch /' – 2011-06-14 14:05:28