【问题标题】:Linux printing alternate 2 lines in text fileLinux在文本文件中打印交替的2行
【发布时间】:2018-12-14 11:18:41
【问题描述】:

我有一个包含以下几行的大文本文件:

(total drops) 0
(bytes output) 111
(total drops) 1
(bytes output) 222
(total drops) 3
(bytes output) 333
(total drops) 3
(bytes output) 444
(total drops) 5
(bytes output) 555
(total drops) 8
(bytes output) 6666
(total drops) 9
(bytes output) 777
(total drops) 10
(bytes output) 888
(total drops) 20
(bytes output) 999
<<SNIP>>

我想(从顶部开始)打印 2 行,跳过接下来的 2 行并再次打印 2 行,依此类推...期望的输出应该是这样的:

(total drops) 0
(bytes output) 111
(total drops) 3
(bytes output) 333
(total drops) 5
(bytes output) 555
(total drops) 9
(bytes output) 777
(total drops) 20
(bytes output) 999

我尝试了各种 sed/awk 但仍然无法正确...

【问题讨论】:

  • 你想做的事情听起来像是一个实现,而不是一个目标。你真正想完成什么?

标签: bash shell


【解决方案1】:

你可以使用这个(awk)

 cat test.txt | awk '{if (((NR % 4)==1) || ((NR % 4)==2)) {print}}'

【讨论】:

    【解决方案2】:

    应该这样做:

    awk '((NR+3)%4)<2' file
    

    这是一个简写

    awk '(((NR+3)%4)<2){print}' file
    

    这是因为模函数NR%4 返回值0,1,2,3。我们需要移动 NR 以使 01 位于正确的位置。因此我们将3 添加到NR。见以下代码:

    $ seq 1 10 | awk '{print NR, NR%4, (NR+3)%4}'
    1 1 0
    2 2 1
    3 3 2
    4 0 3
    5 1 0
    6 2 1
    7 3 2
    8 0 3
    9 1 0
    10 2 1
    

    【讨论】:

      【解决方案3】:

      同样使用 Perl,您可以获得所需的输出

      > cat  skip_lines.txt
      (total drops) 0
      (bytes output) 111
      (total drops) 1
      (bytes output) 222
      (total drops) 3
      (bytes output) 333
      (total drops) 3
      (bytes output) 444
      (total drops) 5
      (bytes output) 555
      (total drops) 8
      (bytes output) 6666
      (total drops) 9
      (bytes output) 777
      (total drops) 10
      (bytes output) 888
      (total drops) 20
      (bytes output) 999
      > perl -ne ' print if $.%4==1 or $.%4==2 ' skip_lines.txt
      (total drops) 0
      (bytes output) 111
      (total drops) 3
      (bytes output) 333
      (total drops) 5
      (bytes output) 555
      (total drops) 9
      (bytes output) 777
      (total drops) 20
      (bytes output) 999
      >
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-03
        • 2013-10-08
        • 2013-12-13
        • 2020-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多