onefish
onechicken
twofish
twochicken
twocows
threechicken
如果我想grep包含「two」的行,但我只想要第二個匹配,該怎麼辦。所以我想要結果「twochicken」。只顯示grep的第n個匹配
onefish
onechicken
twofish
twochicken
twocows
threechicken
如果我想grep包含「two」的行,但我只想要第二個匹配,該怎麼辦。所以我想要結果「twochicken」。只顯示grep的第n個匹配
試試這個:
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
如果字(這裏word == two)在單行中重複多次,&要打印t該線,使用如下:
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想要的,但添加回答我自己的評論。
grep行中的'-m $ n'只是爲了一些優化,不是功能需要的。 – anishsane 2013-02-28 15:05:42
應當注意的是,如果threechicken
和twocows
線進行交換,又名:
onefish
onechicken
twofish
twochicken
threechicken
twocows
然後肯特的第一反應(awk '/two/{i++}i==2' file
)將產生輸出:
twochicken
threechicken
,因爲它需要另一發生匹配以增加計數器。他的最後迴應:awk '/two/{i++}i==2{print; exit}' file
避免了這個問題。
第二個選項是優於文件大小,不是? – poncha 2013-02-28 12:27:18
@poncha,行號 – Kent 2013-02-28 12:31:40
你是什麼意思的'行號'?我的意思是加入'{print;退出}'是任何輸入大小的好主意......哦。這實際上是選項#3;)我算錯了))) – poncha 2013-02-28 12:35:25