onefish
onechicken
twofish
twochicken
twocows
threechicken
如果我想对包含“两个”的行进行 grep,但我只想要第二个匹配项。所以我想要结果“twochicken”。
onefish
onechicken
twofish
twochicken
twocows
threechicken
如果我想对包含“两个”的行进行 grep,但我只想要第二个匹配项。所以我想要结果“twochicken”。
grep -m2 "two" in-file.txt | tail -n1
在第二场比赛后停止,然后打印第二行。
试试这个:
awk '/two/{i++}i==2' file
使用您的数据:
kent$ echo "onefish
onechicken
twofish
twochicken
twocows
threechicken"|awk '/two/{i++}i==2'
twochicken
注意:如果您的文件很大,请执行以下操作:
awk '/two/{i++}i==2{print; exit}' file
grep 和 sed 可用于过滤行号。
测试文件:
onefish
onechicken
twofish
twochicken
threechicken
twocows
获取所需的行:
grep "two" testfile | sed -n 2p
prints "twochicken"
grep "two" testfile | sed -n 1p
prints "twofish"
如果单词(此处为 word==two)在一行中重复多次,并且您想打印该行,请使用以下命令:
word=two
n=2
line=`grep -m$n $word -o -n MyFile | sed -n $n's/:.*//p'`
awk 'FNR=='$line'{print; exit}' MyFile
例如对于以下输入:
onefish
onechicken
twotwofish
twochicken
twocows
threechicken
它将打印twotwofish
,而不是twochicken
.
这可能不是 user1787038 想要的,但添加以回答我自己的评论。
应该注意的是,如果交换了threechicken
和行,也就是:twocows
onefish
onechicken
twofish
twochicken
threechicken
twocows
然后 Kent 的第一个响应 ( awk '/two/{i++}i==2' file
) 将产生输出:
twochicken
threechicken
因为它需要再次出现匹配来增加计数器。他最后的回应:awk '/two/{i++}i==2{print; exit}' file
回避这个问题。
要使用grep
命令进行第 n_th 匹配,我们可以使用head
和tail
命令的组合,如下所示:
grep two file.txt | head -n1 | tail -1
n1
我们需要的第 n 个匹配在哪里。