Count the number of rows in each column of a text file

5,782

Solution 1

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.

Solution 2

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:
5,782

Related videos on Youtube

user1715122
Author by

user1715122

Updated on September 18, 2022

Comments

  • user1715122
    user1715122 over 1 year

    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:
    2
    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?

    • Stéphane Chazelas
      Stéphane Chazelas over 10 years
      awk 'NF!=3' < file.text