【问题标题】:Using sed (or other command line programs) to delete every other X lines使用 sed(或其他命令行程序)删除每隔 X 行
【发布时间】:2018-11-15 05:35:58
【问题描述】:

我有一个巨大的文本文件,它在不同时间对同一事物进行了多次迭代,其基本结构为:

Header (5 lines)
Data (thousands of lines)
Header (5 lines)
Data (thousands of lines)
Header (5 lines)
Data (thousands of lines)

这样重复并持续一段时间。

我想通过删除所有其他 Header + Data 来剔除这个文件。我想我会使用sed,但我不知道怎么做。

每个“循环”都以同一行开头可能会有所帮助(出于本示例的目的,假设它显示为Program X output)并且该确切行仅在每个“循环”的开头出现一次。

谢谢

【问题讨论】:

    标签: sed terminal command line


    【解决方案1】:

    听起来你只需要:

    awk '/Program X output/ && c++{exit} 1' file
    

    例如

    $ seq 50 | awk '/2/ && c++{exit} 1'
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    

    如果这不是您需要的全部,请编辑您的问题以阐明您的要求并向我们展示简洁、可测试的示例输入和预期输出。

    【讨论】:

      【解决方案2】:

      跟踪您看到关键字的频率,并仅在此计数为奇数时打印:

      awk '/Program X output/ {n++} n%2 == 1' <<END
      Program X output
      a
      b
      c
      Program X output
      d
      e
      Program X output
      f
      g
      h
      i
      j
      Program X output
      m
      n
      o
      END
      
      Program X output
      a
      b
      c
      Program X output
      f
      g
      h
      i
      j
      

      【讨论】:

      • 非常感谢,完全解决了。显然,我需要学习如何正确使用 awk,我认为它只对列编辑有用。
      【解决方案3】:

      这可能对你有用(GNU sed):

      sed -r '/Program X output/{x;s/^/x/;x};G;/\n(x{2})*$/!P;d' file
      

      遇到标题行时,将 1 添加到保持空间 (HS) 中的计数器。将 HS 附加到每一行,如果计数器是所需数量的倍数,则仅打印模式空间 (PS) 中的第一行。

      【讨论】:

        猜你喜欢
        • 2013-04-14
        • 1970-01-01
        • 2017-11-09
        • 1970-01-01
        • 2015-10-14
        • 2011-03-21
        • 2021-12-11
        • 2012-02-10
        • 2010-11-14
        相关资源
        最近更新 更多