如何匹配文件中包含某些单词的前三行

How to match the first three lines in the file that contain some word

如何匹配文件中包含单词 racoon 的前三行(从上到下)

例如

127.0.0.1 localhost
18.2.3.122  racoon133
192.9.200.10 exemachine2
18.2.3.123  Aracoon101
10.10.10.10 jank_machine
18.2.3.124  racoon102
18.2.3.125 start10
18.2.3.125 frt100
18.2.3.128  racoon103

预期的结果应该是

18.2.3.122  racoon133
18.2.3.123  Aracoon101
18.2.3.124  racoon102

使用 awk:

awk '/racoon/ { print; if(++ctr == 3) exit }' filename

或者使用 sed:

sed -n '/racoon/ { x; /.../ q; s/$/./; x; p; }' filename

...但也许使用 grep 最理智:

grep -m 3 racoon filename

最后一个可能是 GNU 扩展;我不完全确定 Solaris 的 grep 会接受 -m 3。当然,总有

grep racoon filename | head -n 3

虽然这不会短路(可能是长文件的性能问题)。

另一种 awk 方式

awk 'x<x+=/racoon/;x==3{exit}' file

awk '/racoon/&&++x;x==3{exit}' file