Ben Chuanlong Du's Blog

And let it direct your passion with reason.

Count Number of Fields in Each Line

Sometimes, a structured text file might be malformatted. A simple way to verify it is to count the number of fields in each line.

Using awk

You can count the number of fields in each line using the following awk command. Unfortunately, awk does not take escaped characters into consideration. So this only works for simple formatted (without escaped characters) text files.

awk '{print NF}' filename

Using R

There is a function named count.field in R.

Comments