bash 使用 AWK 根据列数过滤行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3393895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:32:18  来源:igfitidea点击:

Filtering Rows Based On Number of Columns with AWK

linuxbashunixawk

提问by neversaint

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.

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

0333 foo
 bar
23243 qux

yielding only:

只产生:

0333 foo
23243 qux

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

请注意,它们是制表符分隔的,即使对于只有一列的行,您在开头也有制表符。

What's the way to do it?

有什么办法呢?

I tried this but fail:

我试过这个但失败了:

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

enter code here

回答by paxdiablo

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

您需要使用NF(number of fields) 变量来控制操作,例如在以下脚本中:

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

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 awkwill print by default if no rules are matched for a line. The empty command {}guarantees that this will not happen.

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

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 bothcases.

但上面的第一个解决方案在这两种情况下适用。

回答by ghostdog74

awk 'NF==2' file

回答by Vijay

awk '(NF==2){print}' test.txt