【发布时间】:2019-05-22 15:20:30
【问题描述】:
我想显示包含单词的前 3 行和最后 2 行。 我尝试了一个 grep 命令,但它没有显示我想要的内容。
grep -w it /usr/include/stdio.h | head -3 | tail -2
它只显示其中包含“it”的第 2 行和第 3 行。
【问题讨论】:
我想显示包含单词的前 3 行和最后 2 行。 我尝试了一个 grep 命令,但它没有显示我想要的内容。
grep -w it /usr/include/stdio.h | head -3 | tail -2
它只显示其中包含“it”的第 2 行和第 3 行。
【问题讨论】:
你可以简单地追加 head 和 tail 的结果:
{ head -3 ; tail -2 ;} < /usr/include/stdio.h
【讨论】:
这里的问题是tail 永远不会收到grep 的输出,而只会收到文件的前3 行。为了使这项工作可靠,您需要grep 两次,一次使用head,一次使用tail 或多路复用流,例如:
grep -w it /usr/include/stdio.h |
tee >(head -n3 > head-of-file) >(tail -n2 > tail-of-file) > /dev/null
cat head-of-file tail-of-file
在这里输出:
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
The GNU C Library is distributed in the hope that it will be useful,
or due to the implementation it is a cancellation point and
/* Try to acquire ownership of STREAM but do not block if it is not
【讨论】:
head和tail,另一方面sed可以做到
你应该试试这个
grep -A 2 -B 3 "it" /usr/include/stdio.h
-A = 匹配单词“it”的 2 行上下文之后
-B = 匹配单词“it”的 3 行上下文后
如果您确实需要正则表达式,也可以添加 -W。
预期输出:
第 1 行
第 2 行
包含它的行
第 4 行
第 5 行
第 6 行
【讨论】:
cat /usr/include/stdio.h | grep -w it | head -3 | tail -2
【讨论】: