使用AWK根据列数过滤行 [英] Filtering Rows Based On Number of Columns with AWK

查看:602
本文介绍了使用AWK根据列数过滤行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几行数据包含 单列和两列.我想做的是 提取仅包含2列的行.

I have lines of data that contain single column and two columns. What I want to do is to extract lines that contain only 2 columns.

0333 foo
 bar
23243 qux

仅屈服:

0333 foo
23243 qux

请注意,即使对于只有一列的行,它们也是制表符分隔的 您一开始就有标签页.

Note that they are tab separated, even for lines with only one column you have tab at the beginning.

这是怎么做的?

我尝试了这个但失败了:

I tried this but fail:

awk '$1!="";{print $1 "\t" $2}' myfile.txt

enter code here

推荐答案

您需要使用NF(字段数)变量来控制操作,例如以下记录:

You need to use the NF (number of fields) variable to control the actions, such as in the following transcript:

$ echo '0333 foo
>  bar
> 23243 qux' | awk 'NF==2{print}{}'
0333 foo
23243 qux

如果字段数为2,将打印该行,否则将不执行任何操作.我有一个(看似)奇怪的构造NF==2{print}{}的原因是,如果在一行中没有匹配的规则,则默认情况下将打印awk的某些实现.空命令{}保证不会发生这种情况.

This will print the line if the number of fields is two, otherwise it will do nothing. The reason I have the (seemingly) strange construct NF==2{print}{} is because some implementations of awk will print by default if no rules are matched for a line. The empty command {} guarantees that this will not happen.

如果您很幸运地拥有其中一个不这样做的人,那么您可以逃脱:

If you're lucky enough to have one of those that doesn't do this, you can get away with:

awk 'NF==2'

,但是上面的第一个解决方案在两种情况下都适用.

but the first solution above will work in both cases.

这篇关于使用AWK根据列数过滤行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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