bash 仅显示 grep 的第 n 个匹配项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15135430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:24:06  来源:igfitidea点击:

Display only the n'th match of grep

bashgreppattern-matchingmatch

提问by Andrew Tsay

onefish
onechicken
twofish
twochicken
twocows
threechicken

What if I want to grep for lines containing "two", but I only want the 2nd match. So I want the result "twochicken".

如果我想 grep 包含“两个”的行,但我只想要第二场比赛怎么办。所以我想要结果“twochicken”。

采纳答案by Kent

try this:

尝试这个:

awk '/two/{i++}i==2' file

with your data:

使用您的数据:

kent$  echo "onefish
onechicken
twofish
twochicken
twocows
threechicken"|awk '/two/{i++}i==2'
twochicken

note: if your file is huge, do this:

注意:如果您的文件很大,请执行以下操作:

awk '/two/{i++}i==2{print; exit}' file

回答by John Zwinck

grep -m2 "two" in-file.txt | tail -n1

Stop after the second match, then take the second line printed.

在第二场比赛后停止,然后打印第二行。

回答by Joy

grep and sed can be used to filter the line number.

grep 和 sed 可用于过滤行号。

testfile:

测试文件

onefish
onechicken
twofish
twochicken
threechicken
twocows

Getting the desired line:

获取所需的行:

grep "two" testfile | sed -n 2p
prints "twochicken"

grep "two" testfile | sed -n 1p
prints "twofish"

回答by anishsane

If the word (here word==two) repeats multiple time in a single line, & you want to print that line, use below:

如果单词(此处为 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 

e.g. For below input:

例如对于以下输入:

onefish
onechicken
twotwofish
twochicken
twocows
threechicken

it will print twotwofish, instead of twochicken.

它将打印twotwofish,而不是twochicken.

This may not be what user1787038 wants, but added to answer my own comment.

这可能不是 user1787038 想要的,而是为了回答我自己的评论而添加的。

回答by Alex

It should be noted that if the threechickenand twocowslines were swapped, aka:

应该注意的是,如果threechickentwocows线交换了,也就是:

onefish
onechicken
twofish
twochicken
threechicken
twocows

then Kent's first response (awk '/two/{i++}i==2' file) would yield the output:

那么 Kent 的第一个响应 ( awk '/two/{i++}i==2' file) 将产生输出:

twochicken
threechicken

because it takes another occurrence of the match to increment the counter. His last response: awk '/two/{i++}i==2{print; exit}' fileavoids this issue.

因为它需要再次发生匹配才能增加计数器。他最后的回应是:awk '/two/{i++}i==2{print; exit}' file避免了这个问题。