Linux在文本文件中打印备用2行

时间:2018-12-13 22:52:17

标签: bash shell

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

(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,但仍然无法正确完成...

3 个答案:

答案 0 :(得分:0)

您可以使用此(确认)

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

答案 1 :(得分:0)

这应该做到:

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

答案 2 :(得分:0)

同样使用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
>