简体   繁体   English

如何使用SED或AWK删除除第一行以外的奇数行

[英]How to remove odd lines except for first line using SED or AWK

I have the following file 我有以下文件

# header1 header2
zzzz yyyy
1
kkkkk wwww
2

What I want to do is to remove odd lines except the header yielding: 我想要做的是删除奇数行除了标题产生:

# header1 header2
zzzz yyyy
kkkkk wwww

I tried this but it removes the header too 我尝试了这个,但它也删除了标题

awk 'NR%2==0'

What's the right way to do it? 什么是正确的方法呢?

awk 'NR==1 || NR%2==0'

If the record number is 1 or is even, print it. 如果记录编号为1或是偶数,请将其打印出来。

awk 'NR % 2 == 0 || NR == 1'

Reversing the comparisons might be marginally faster. 反转比较可能会略微加快。 The difference probably isn't measurable. 差异可能无法衡量。 (And the choice of spacing is essentially immaterial too.) (并且间距的选择也基本上是无关紧要的。)

Works on GNU sed 适用于GNU sed

sed '3~2d' ip.txt 

This deletes line numbers starting from 3rd line and then +2,+4,+6, etc 这将删除从第3行开始的行号,然后是+ 2,+ 4,+ 6等

Example: 例:

$ seq 10 | sed '3~2d'
1
2
4
6
8
10

You just need 您只需要

awk 'NR==1 || NR%2==0' file
  • This keeps the header part of the file intact and applies the rule NR%2==0 , which is true only for even lines(starting from the header) in which case it is printed. 这使文件的标题部分保持不变并应用规则NR%2==0 ,这对于偶数行(从标题开始)是正确的,在这种情况下它被打印。

Another variant of the same above answer 上述答案的另一种变体

awk 'NR==1 || !(NR%2)' file
  • For even lines (NR%2) becomes 0 and negation of that becomes a true condition to print the line 对于偶数行(NR%2)变为0并且否定成为打印行的真实条件
sed '1!{N;P;d}'

1! On lines other than the first (the default behavior echoes the first line) 在第一行以外的行上(默认行为与第一行相呼应)
N append the next line to the current line N将下一行附加到当前行
P print only the first of the two P只打印两个中的第一个
d delete them both. d删除它们。

This might work for you (GNU sed): 这可能适合你(GNU sed):

sed '1b;n;d' file

But: 但:

sed '3~2d' file

Is far neater. 更整洁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM