我正在尝试编写一个脚本,如果第一个字段具有相同的模式,它只会greps。我想grep三次具有相同数字的行。请看下面。谢谢大家!!!
1 Cat
1 Dog
1 Mouse
2 Cat
3 Cat
3 Dog
4 Cat
4 Dog
4 Mouse
输出应如下所示:
1 Cat
1 Dog
1 Mouse
4 Cat
4 Dog
4 Mouse
答案 0 :(得分:1)
首先在整个文件中啜食
会更容易 # (?m)^(\d+)(?!\d).*\s*(?:^\1(?!\d).*\s*){2}
(?m)
^
( \d+ ) (?! \d )
.* \s*
(?:
^
\1 (?! \d )
.* \s*
){2}
Perl测试用例
$/ = undef;
$str = <DATA>;
while ( $str =~ /(?m)^(\d+)(?!\d).*\s*(?:^\1(?!\d).*\s*){2}/g)
{
print "Matched:\n$&\n";
}
__DATA__
1 Cat
1 Dog
1 Mouse
2 Cat
3 Cat
3 Dog
4 Cat
4 Dog
4 Mouse
输出&gt;&gt;
Matched:
1 Cat
1 Dog
1 Mouse
Matched:
4 Cat
4 Dog
4 Mouse
答案 1 :(得分:1)
如果您的数据如上所述(即具有相同数字的行是连续的,每行后跟两行换行),您可以这样做:
while ($data =~ /^(([0-9]++).*(?:\R\R\2 .*){2})/mg) {
$_ .= $1 . "\n\n";
}
chomp;
print;