Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of fields returned by awk

Tags:

awk

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

a b c d 

so, awk --field-separator=" " | <something> should return 4

like image 458
Sriram Avatar asked Apr 07 '11 14:04

Sriram


People also ask

How do I count the number of fields in awk?

awk with NF (number of fields) variable. NF is a built-in variable of awk command which is used to count the total number of fields in each line of the input text.

What does GSUB do in awk?

The gsub() function returns the number of substitutions made. If the variable to search and alter ( target ) is omitted, then the entire input record ( $0 ) is used.

What is awk '{ print $1 }'?

If you notice awk 'print $1' prints first word of each line. If you use $3, it will print 3rd word of each line.

What is NF in awk?

NF is a predefined variable whose value is the number of fields in the current record. awk automatically updates the value of NF each time it reads a record. No matter how many fields there are, the last field in a record can be represented by $NF . So, $NF is the same as $7 , which is ' example.


1 Answers

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

like image 190
Douglas Meyer Avatar answered Sep 24 '22 18:09

Douglas Meyer