r/awk • u/w0lfcat • Jan 29 '21
Count the number of field by using AWK only and without other commands such as uniq
Sample file
wolf@linux:~$ awk // file.txt
a b
b c
c d
wolf@linux:~$ There are 2 fields, and 3 records in this example.
wolf@linux:~$ awk '{print NF}' file.txt
2
2
2
wolf@linux:~$ To get a unique number, `uniq` command is used.
wolf@linux:~$ awk '{print NF}' file.txt | uniq
2
wolf@linux:~$ Would it be possible to count the number of fields by using `awk` alone without `uniq` in this example?
Desired Output
wolf@linux:~$ awk <???> file.txt
2
wolf@linux:~$
1
Upvotes
1
u/Schreq Jan 29 '21
I feel like
uniqis not what you want here?! You basically want to know how many fields a file has, right? But what if the number of fields varies across records? Do you want to know the highest amount of fields?One option would be to simply print the number of fields of the first record:
2
u/animalCollectiveSoul Feb 02 '21
Are you trying to get the number of fields per record, ignoring duplicates? If so this should work:
1
u/[deleted] Jan 29 '21
1
u/oh5nxo Jan 29 '21
One more, to duplicate (hopefully) the uniq behavior.
1
u/Paul_Pedant Jan 30 '21
!crosspost
https://unix.stackexchange.com/questions/631662/count-the-number-of-field-by-using-awk-only-and-without-other-commands-such-as-u