繁体   English   中英

从文本文件中删除奇数或偶数行

[英]Remove odd or even lines from a text file

我需要删除文本文件中的奇数行以进行下采样。 我找到了这个命令,

awk 'NR%2==0' file

但它只在终端中打印奇数行。 如何真正去除它们?

我真的不关心偶数或奇数,我希望它们从文件中删除或打印在另一个文件中。 这只会在终端中打印它们。

awk

%是模数运算符, NR是当前行号,因此NR%2==0仅对偶数行为真,并将为它们调用默认规则( { print $0 } )。 因此,只保存偶数行,将输出从awk重定向到一个新文件:

awk 'NR%2==0' infile > outfile

sed

你可以用sed完成同样的事情。 devnulls答案显示了如何使用GNU sed做到这一点。 以下是没有~运算符的sed版本的替代方案:

保持奇数行

sed 'n; d' infile > outfile

保持均匀的线条

sed '1d; n; d' infile > outfile

使用 GNU sed:

sed -i '0~2d' filename

从文件中删除偶数行。

删除奇数行:

sed -i '1~2d' filename

-i选项会导致将更改就地保存到文件中。

引用手册:

`FIRST~STEP'
     This GNU extension matches every STEPth line starting with line
     FIRST.  In particular, lines will be selected when there exists a
     non-negative N such that the current line-number equals FIRST + (N
     * STEP).  Thus, to select the odd-numbered lines, one would use
     `1~2'; to pick every third line starting with the second, `2~3'
     would be used; to pick every fifth line starting with the tenth,
     use `10~5'; and `50~0' is just an obscure way of saying `50'.

这可能对您有用(GNU 和非 GNU sed):

 sed -n 'p;n' file # keep odd
 sed -n 'n;p' file # keep even

-n : 禁止打印

p : 打印当前行

n : 下一行

不要关注负面(删除线条),专注于正面(选择线条),您的解决方案将效仿。 因此,您应该认为I need to select even lines而不是I need to remove odd lines I need to select even lines ,然后解决方案很简单:

awk '!(NR%2)' file

如果要将结果保存到新文件:

awk '!(NR%2)' file > newfile

或回到原来的:

awk '!(NR%2)' file > newfile && mv newfile file

这是一个awk示例,用于创建分别包含奇数行和偶数行的两个新文件:

awk '{ if (NR%2) print > "odd.txt"; else print > "even.txt" }' input.txt

用于将事件打印到新文件的 Perl 解决方案:

perl -lne 'print if $. % 2 == 0' infile > outfile

要打印赔率, == 1更改为== 0

$. 是行号

在原始文件中只保留偶数:

perl -i -lne 'print if $. % 2 == 0' infile

与上面相同,但创建一个名为 infile.bak 的备份文件:

perl -i.bak -lne 'print if $. % 2 == 0' infile

暂无
暂无

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

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