Richard C
Richard C

Reputation: 411

awk to find number of columns for each line and exit if more than required

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

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 -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?

Upvotes: 13

Views: 21581

Answers (1)

anubhava
anubhava

Reputation: 785098

It appears that you want to print first row with 2 columns and exit immediately. This awk command should work:

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

An equivalent sed command would also help here:

sed -E '/[^,]+,/q;d' file

BOO,HOO

Upvotes: 17

Related Questions