从文本文件中删除奇数或偶数行 [英] Remove odd or even lines from a text file
问题描述
我需要删除文本文件中的奇数行以进行下采样.我找到了这个命令,
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.
推荐答案
awk
%
是模运算符,NR
是当前行号,所以 NR%2==0
仅对偶数为真行并将为其调用默认规则({ print $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 答案显示了如何使用 GNU sed
.以下是没有 ~
运算符的 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 > outfile
保持连线
sed '1d; n; d' infile > outfile
这篇关于从文本文件中删除奇数或偶数行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!