【问题标题】:grep tail and head wrong resultgrep tail 和 head 错误的结果
【发布时间】:2019-05-22 15:20:30
【问题描述】:

我想显示包含单词的前 3 行和最后 2 行。 我尝试了一个 grep 命令,但它没有显示我想要的内容。

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

它只显示其中包含“it”的第 2 行和第 3 行。

【问题讨论】:

    标签: linux grep tail head


    【解决方案1】:

    你可以简单地追加 head 和 tail 的结果:

    { head -3 ; tail -2 ;} < /usr/include/stdio.h
    

    【讨论】:

      【解决方案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:你不能用headtail,另一方面sed可以做到
      • @Thor 这不是真的,请参阅 MahmoudKsemtini 回答
      • @FernandoSantagata:很有趣。但是,该解决方案仅适用于从文件重定向,而不是在管道中,所以我认为我的观点仍然存在
      【解决方案3】:

      你应该试试这个

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

      -A = 匹配单词“it”的 2 行上下文之后

      -B = 匹配单词“it”的 3 行上下文后

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

      预期输出:

      第 1 行

      第 2 行

      包含它的行

      第 4 行

      第 5 行

      第 6 行

      【讨论】:

      • 打印所有文件
      • 这个词在整个文件中是否重复?如果是这样,那么整个文件可能是输出。说如果第二行匹配,那么将打印第 1 行到第 5 行,下一个匹配在第 5 行,然后将打印第 6 到第 8 行,依此类推
      • 你能发一份文件的片段吗?
      • 这是位于 /usr/include 的 stdio.h 文件
      【解决方案4】:
      cat /usr/include/stdio.h | grep -w it | head -3 | tail -2
      

      【讨论】:

        猜你喜欢
        • 2015-12-26
        • 1970-01-01
        • 1970-01-01
        • 2016-10-30
        • 1970-01-01
        • 1970-01-01
        • 2017-10-17
        • 2012-12-16
        • 1970-01-01
        相关资源
        最近更新 更多