删除文本文件奇数或偶数行,在Linux终端 [英] remove odd or even lines from text file in terminal in linux
问题描述
我需要删除奇数行的文本文件,以使下采样。我发现这个命令,
I need to remove odd lines in a text file to make a down-sampling. I've found this command,
awk 'NR%2==0' file
但只打印终端中的奇数行。如何真正删除它们?
but it only prints the odd lines in the terminal. How to really remove them?
我真的不关心偶数或奇数,我希望他们从文件中删除,或在另一个文件打印。仅打印他们在终端。
I don't really care for even or odd, I want them removed from the file or printed in another file. This only prints them in the terminal.
推荐答案
的%
是一个模操作符和 NR
是当前行号,所以 NR%2 == 0
仅在偶数行的真实,将调用它们的默认规则( {$打印0}
)。因此,要的只保存偶数行的,从重定向 AWK
输出到一个新文件:
awk
The %
is a modulus operator and NR
is the current line number, so NR%2==0
is true only for even lines and will invoke the default rule for them ({ print $0 }
). Thus to save only the even lines, redirect the output from awk
to a new file:
awk 'NR%2==0' infile > outfile
SED
您可以用完成 SED
同样的事情。 的 devnulls 的的回答显示了如何 sed的GNU $办呢C $ C>。
下面是版本替代 SED
不具备的〜
运营商:
sed
You can accomplish the same thing with sed
. devnulls answer shows how to do it with GNU sed
.
Below are alternatives for versions of sed
that do not have the ~
operator:
的删除偶数行的
sed 'n; d' infile # output ODD lines only
的删除奇数行的
sed '1d; n; d' infile # output EVEN lines only
这篇关于删除文本文件奇数或偶数行,在Linux终端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!