如何匹配文件中包含单词 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
答案 0 :(得分:2)
使用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
虽然没有短路(长文件可能会出现性能问题)。
答案 1 :(得分:2)
另一种方式
awk 'x<x+=/racoon/;x==3{exit}' file
或
awk '/racoon/&&++x;x==3{exit}' file