bash awk 查找每行的列数,如果多于需要则退出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30624274/
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
awk to find number of columns for each line and exit if more than required
提问by Richard C
I'm trying to read a file line by line and check to see if the current line contains more than one column. if it contains more than one, I want the script to abort.
我正在尝试逐行读取文件并检查当前行是否包含多于一列。如果它包含多个,我希望脚本中止。
I have a file called test and it contains the following...
我有一个名为 test 的文件,它包含以下内容...
ME
TEST
HELLO
WORLD
BOO,HOO
BYE BYE
I've found using awk that I can get the count of columns by using the following...
我发现使用 awk 可以通过使用以下内容来获取列数...
awk -F',' '{print NF}' test
and this returns...
这返回...
1
1
1
1
2
1
Is there a way to have the script exit after the '2' is found and print an Error stating $1 (in this case BOO,HOO) contains two columns?
有没有办法让脚本在找到“2”后退出并打印一个错误,指出 $1(在本例中为 BOO,HOO)包含两列?
回答by anubhava
Sure you can do:
当然你可以这样做:
awk -F, 'NF > 1{exit} 1' file
This will give output as:
这将给出如下输出:
ME
TEST
HELLO
WORLD
as NF>1
condition exits the awk as soon as there are more than 1 columns.
因为NF>1
一旦超过 1 列,条件就会退出 awk。
EDIT:As per comments below OP wants to print first row with 2 columns and exit. This command should work:
编辑:根据下面的评论,OP 想要打印 2 列的第一行并退出。这个命令应该可以工作:
awk -F, 'NF > 1{print; exit}' file
BOO,HOO