删除文本文件奇数或偶数行,在Linux终端 [英] remove odd or even lines from text file in terminal in linux

查看:479
本文介绍了删除文本文件奇数或偶数行,在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
下面是版本替代 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆