grep、tail和head命令返回错误结果。

3
我想展示包含某个单词的前三行和后两行。我尝试使用grep命令,但它没有显示我想要的内容。 grep -w it /usr/include/stdio.h | head -3; grep -w it /usr/include/stdio.h | tail -2 它只显示包含"it"的第二和第三行。
4个回答

2

这里的问题是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

它可以工作,但我被要求只使用一个命令完成。我该如何同时对头部和尾部进行两次grep操作? - avanabana
@avanabana:你不能使用 headtail,但是 sed 可以做到。 - Thor
@Thor,那不是真的,请看MahmoudKsemtini的回答。 - Fernando Santagata
@FernandoSantagata:有趣。然而,该解决方案仅适用于从文件重定向,而不是在管道中使用,因此我认为我的观点仍然成立。 - Thor

2
你可以简单地将head和tail的结果拼接起来:
{ head -3 ; tail -2 ;} < /usr/include/stdio.h

0
cat /usr/include/stdio.h | grep -w it | head -3 | tail -2

0

你应该试一下这个

grep -A 2 -B 3 "it" /usr/include/stdio.h

-A = 在匹配到“it”单词之前的2行内容之后

-B = 在匹配到“it”单词之前的3行内容之后

如果确实需要正则表达式,也可以添加-W选项。

期望输出:

第1行

第2行

包含“it”单词的行

第4行

第5行

第6行


它打印出所有文件。 - avanabana
单词 "it" 是否在整个文件中多次重复出现?如果是,则整个文件可能是输出。例如,如果第二行匹配,则将打印第1行到第5行,下一个匹配在第5行上,则将打印第6行到第8行,以此类推。 - yoga
可以发一下文件的片段吗? - yoga
它是位于 /usr/include 的 stdio.h 文件。 - avanabana

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接