I have a text file with the following format:

5 3 1
2 3 4
i.e. space separated 3 columns of numbers/ However, some of the rows may be like:
3 1
So, I want to detect if the text file has any such inconsistencies and to print them out. How do I do this?


Stephane Chazelas suggested

awk 'NF != 3'

This is a simple way of printing all the lines that don't have exactly three columns. If you also want the command to return a failure status if any such line is found:

awk 'NF != 3 {print; ++bad} END {exit(!!bad)}'

Remove print; to not print anything and only report the presence of such lines through the exit status.

You can also do this with grep:

grep -Ev '^[^ ]+ +[^ ]+ +[^ ]+$'

If you want to be more strict and print all the lines that don't consist of exactly three columns each containing an integer:

grep -Ev '^([0-9]+) +([0-9]+) +([0-9]+)$'

Use [␉ ]+ instead of  + where is a tab character if you want to allow one or more tab as column separators. Use (␉| +) to allow either exactly one tab or a sequence of spaces.


In case what you really want is what is asked in your question's title, this awk command will print the line number and number of fields in each line:

awk '{print NR,NF}'
awk '{if(NF != 3) print NR,NF}' file.txt

This will print the row numbers in the file that do not have 3 fields and the number of fields they have.

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.