[How To] How to count the number of coulumns in each row in a text file

In this tutorial, we would be using awk command to count the number of columns in each row in a text file.The awk command has multiple built in variable that let us define the row, column delimiters.

Supposing we have a pipe separated file called 'count_me.dat' with 12 rows in it. Also, each row has different number of columns. In such a case, below awk command can be used to count the number of columns in each file.

$ awk -F'|' '{print NR,NF; N++}' count_me.dat

::Syntax Explanation::

-F'|' - Tells the awk command that the field separator for the file is '|', pipe.
print NR, NF - Tells the awk command to print the row number and field number.
N++ - Increments the line count to the next line.
count_me.dat - Name of the input file.

::Sample Screen-shot::


awk command to count the number of columns in each row [click on the image to enlarge]