#147 Count the total number of fields in a file using awk

Assume we have “test1.txt” file with data in columns:

a b c d
e f g h
i j k l
1 2 3 4

Save the following awk script in the file “ex147.awk”

#!/bin/awk -f
{ total += NF } 
END { print total }

Run file “ex147run.txt”

awk -f ex147.awk test1.txt

using

./ex147run.txt

The result is 16.