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?
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 : ).
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}' .
awk '{ print $2; }' prints the second field of each line. This field happens to be the process ID from the ps aux output.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With