awk question

Hi All,

I am studying the AWK tutorial and found this line of code and unable to understand correctly.

Q - Print the length of the longest input line:

awk '{ if (length($0) > max) max = length($0) }
END { print max }' data

As per my understanding, the length function reading the first line and comparing with max, then max is assigned to first line.

It compares all lines and print max at last. Is my understanding correct. One more question i have is, can we assign a value after comparing. I generally know we have to assign values before any comparison. Please some one explain this.

Thanks, Nagesh

Hi,

In awk all variables are initiated with a default value, which is "", and is equal to 0 in a numeric context.

On the first line the value for max is equal to this default value, and so length($0) is larger than 0 (the comparison is numerical), so then max is assigned length($0) ..

2 Likes