38

Is there a way to get awk to return the number of fields that meet a field-separator criteria? Say, for instance, the file contains:

a b c d

So, awk -F=' ' | <something> should return 4.

Mehdi Charife
  • 722
  • 1
  • 7
  • 22
Sriram
  • 10,298
  • 21
  • 83
  • 136

4 Answers4

72

The NF variable is set to the total number of fields in the input record. So:

echo "a b c d" | awk --field-separator=" " "{ print NF }"

will display

4

Note, however, that:

echo -e "a b c d\na b" | awk --field-separator=" " "{ print NF }"

will display:

4
2

Hope this helps, and happy awking

Douglas Meyer
  • 1,561
  • 12
  • 12
6

NF gives the number of fields for a given record:

[]$ echo "a b c d" | gawk '{print NF}'
4
Mark Wilkins
  • 40,729
  • 5
  • 57
  • 110
2

If you would like to know the set of all the numbers of fields in a multiline content you can run:

X | awk '{print NF}' | sort -n | uniq

being X a command that outputs content in the standard output: cat, echo, etc. Example:

With file.txt:

a b
b c
c d
e t a
e u

The command cat file.txt | awk '{print NF}' | sort -n | uniq will print:

2
3

And with file2.txt:

a b
b c
c d
e u

The command cat file2.txt | awk '{print NF}' | sort -n | uniq will print:

2
axelbrz
  • 783
  • 1
  • 7
  • 16
2

awk(1) on FreeBSD does not recognize --field-separator. Use -v instead:

echo "a b c d" | awk -v FS=" " "{ print NF }"

It is a portable, POSIX way to define the field separator.

Mateusz Piotrowski
  • 8,029
  • 10
  • 53
  • 79