使用 AWK 根据列数过滤行
我有几行数据包含 单列和两列。我想做的是 提取仅包含 2 列的行。
0333 foo
bar
23243 qux
仅产生:
0333 foo
23243 qux
请注意,即使对于只有一列的行,它们也是制表符分隔的 你在开头有标签。
有什么方法可以做到呢?
我尝试过这个但失败了:
awk '$1!="";{print $1 "\t" $2}' myfile.txt
enter code here
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
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 '$1!="";{print $1 "\t" $2}' myfile.txt
enter code here
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要使用
NF
(字段数)变量来控制操作,例如在以下记录中:如果字段数为两个,则将打印该行,否则将不执行任何操作。我使用(看似)奇怪的构造
NF==2{print}{}
的原因是,如果没有与某个规则匹配的规则,awk
的某些实现将默认打印线。空命令{}
保证不会发生这种情况。如果您足够幸运,拥有一个不这样做的解决方案,那么您可以逃脱:
但上面的第一个解决方案在两种情况下都适用。
You need to use the
NF
(number of fields) variable to control the actions, such as in the following transcript: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 ofawk
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:
but the first solution above will work in both cases.