I intend to use ‘awk’ on a dummy file, to get the line with maximum number of fields/words in it – considering, I am using whitespace as “FS(field seperator)”.
My dummyfile is as:
awk {print} awkexfile.txt
This
is
an
example
file,
which
we
will
use
for
awk
actionsThis is a seperate line in this file
This is a line, with comma – ,
This is a line, with
I am trying to print line
(and as a perk, also get the corresponding line number NR of that record).
awk '{if (length($0) > max) max = length($0)} END {if (NF == max) print NR max}' awkexfile.txt
I was expecting an output like:
15 This is a seperate line in this file
I don’t get any output for the above command.
I’m not sure, if once END is encountered by parser, does the awk parser get back to the line with NF == max
1
Your code prints nothing because NR at END is 5 (5 lines total in input), which is not equal to the number of chars in the longest line (36). You want to get the line with the largest number of words/fields (not chars). Try this:
'{if (NF>theNumberOfWords){theLine=$0; theLineNumber=NR; theNumberOfWords=NF}} END {print "line = <"theLine">,","line number=<"theLineNumber">,","number of words =<"theNumberOfWords">"}'