0

I have a csv that looks as follows:

column1, column2, column3, column4, column5,
1,,,,5,
1,2,3,,,
1,2,3,4,5
1,2,3,4,5,
1,2,,,5,

Using awk I want to print the number of all the rows and a comment "CORRECT" if the column has no empty fields and "ERROR" if the column contains one or more empty fields.

I have this:

cat test_results.csv | awk -F"," '{for(i=1;i<=NF;i++) if($i=="") print NR, "ERROR"; else print NR, "CORRECTO"}'
1 CORRECTO
1 CORRECTO
1 CORRECTO
1 CORRECTO
1 CORRECTO
1 ERROR
2 CORRECTO
2 ERROR
2 ERROR
2 ERROR
2 CORRECTO
and so on 

Unfortunately this command searches for every null space in a row and gives back the row number for every empty and correct field it encounters.

How can I change it to get single number of each column with a comment "CORRECT" if there are no empty fields in a column or ERROR if there is one or more empty filed in it?

Desired output:

1 ERROR
2 ERROR
3 ERROR
4 CORRECT
5 ERROR
6 ERROR
1
  • your title is saying "print number of column ...", but in your code and your expected output you print the line number. so which is true? also verify my edit in parallel . May 2 at 18:07
1
$ awk -F, '{ count=0; for(i=1; i<=NF; i++) count+=$i=="" 
           print NR, count? "ERROR" :"CORRECT";
}' infile
1 ERROR
2 ERROR
3 ERROR
4 CORRECT
5 ERROR
6 ERROR

if you want print the count of the empty columns instead of line number:

$ awk -F, '{ count=0; for(i=1; i<=NF; i++) count+=$i==""
             print count? count " ERROR":"All CORRECT"
  }' infile
1 ERROR
4 ERROR
3 ERROR
All CORRECT
1 ERROR
3 ERROR
0
1
$ awk '{print NR, (/^,|,,|,$/ ? "ERROR" : "CORRECT")}' file
1 ERROR
2 ERROR
3 ERROR
4 CORRECT
5 ERROR
6 ERROR
0

I would use awk for this purpose.

awk -F',' '{for(i=1;i<=NF;i++) { if($i=="") error[NR]++} print (error[NR])? NR " ERROR":NR " CORRECT"}' file.csv

for(i=1;i<=NF;i++) { if($i=="") error[NR]++}. This expression sees for empty columns($1=="") and whenever this finds an empty column, error[NR] value is increased by 1. If this finds no empty column then error[NR] is false. For instance there is no error[4] value. Let's see:

awk -F',' '{for(i=1;i<=NF;i++) { if($i=="")  error[NR]++ } print "error[" NR"] =", error[NR]}' file.csv
error[1] = 1
error[2] = 4
error[3] = 3
error[4] = 
error[5] = 1
error[6] = 3

Because error[4] is false, therefore statement after : NR " CORRECT"}' is printed. If error[NR] is true, statement after ? is printed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.