Thursday, 6 September 2018

Awk does not print the expected result of the file

In the awk below I expected that adding NR==2 would only print check the 2nd line $1value, the 1 and ensure that it is a number. If it is then print Index is a number else Index is not a number. It seems close but the results is not expected... maybe I used the wrong variable? Thank you :).
file.txt
Index   Chr Start   End Ref Alt Quality Freq    Score   HGMD
1   1   10  100 A   -   GOOD    .002    2   .
2   1   100 1000    -   C   STRAND BIAS .036    10  .
3   5   50  500 AA  T   GOOD    1   5   .

awk
awk -F'\t' 'NR==2 $1 ~ /^[[:digit:]]/ {print "Index is a number"} ELSE {print "Index is not a number"}' file.txt
Index is a number
Index is a number
Index is a number
Index is a number
Index is a number

desired output
Index is a number


awk 'NR==2 {print "Index is "($2~/^[0-9]+$/?"":"not ") "a number";exit}' file

  • If you just want to check line 2, you have to exit after the processing
  • If you need other Field Separator, add -F option

0 comments:

Post a Comment