Awk to find the number of columns for each row and exit if more than required

I am trying to read a file line by line and check if the current line contains more than one column. if it contains more than one, I want the script to be interrupted.

I have a file called test and it contains the following ...

ME
TEST
HELLO
WORLD
BOO,HOO
BYE BYE

I found using awk to get the number of columns using the following ...

awk -F',' '{print NF}' test

and it returns ...

1
1
1
1
2
1

Is there a way to make a script output after detecting "2" and print the error message "$ 1" (in this case, BOO, HOO) contains two columns?

+4
source share
1 answer

Of course you can do:

awk -F, 'NF > 1{exit} 1' file

This will give a result like:

ME
TEST
HELLO
WORLD

NF>1 awk, 1 .


EDIT: OP . :

awk -F, 'NF > 1{print; exit}' file
BOO,HOO
+5

All Articles