Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
awk 'NF!=3' < file.text – Stéphane Chazelas Oct 6 '13 at 21:10
thanks, that helps.. – user1715122 Oct 6 '13 at 21:14
up vote 5 down vote accepted

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.

share|improve this answer

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}'
share|improve this answer
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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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