Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

exit

awk

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?

like image 735
Richard C Avatar asked Jun 03 '15 15:06

Richard C


People also ask

What is awk '{ print $4 }'?

The AWK language is useful for manipulation of data files, text retrieval and processing. -F <value> - tells awk what field separator to use. In your case, -F: means that the separator is : (colon). '{print $4}' means print the fourth field (the fields being separated by : ).

How do I find the number of columns in awk?

Method 2: Using head + awk Commands The awk command option -F retrieves the field separators on the first row of the CSV file which is then printed as numeric (-N) characters by the command portion '{print NF}' .

What is awk '{ print $2 }'?

awk '{ print $2; }' prints the second field of each line. This field happens to be the process ID from the ps aux output.

What is awk '{ print $1 }'?

awk treats tab or whitespace for file separator by default. Awk actually uses some variables for each data field found. $0 for whole line. $1 for first field. $2 for second field.


1 Answers

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.


EDIT: As per comments below OP wants to print first row with 2 columns and exit. This command should work:

awk -F, 'NF > 1{print; exit}' file
BOO,HOO
like image 106
anubhava Avatar answered Oct 12 '22 11:10

anubhava