How to use the maximum number for each line in awk?


Here is a simple awk script max1.awk to get the max length of all lines.

#! /usr/bin/awk
BEGIN {max =0 }
    if (length($0) > max) { max = length($0)}
END {print max}

It can get max length with some test file.

awk -f max1.awk  test_file

Now to move all awk script into BEGIN block as below max2.awk.

#! /usr/bin/awk
BEGIN {max =0;
    if (length($0) > max) { max = length($0)};
    print max}

Why can't print max length on test_file with awk -f max2.awk test_file?
How can i use the max number for every line ?

The BEGIN block will be processed before awk reading lines, if your script has only BEGIN block, no line will be loaded, only BEGIN blocked was executed by awk.

Thus, your max length calculation was not done.


kent$  awk 'BEGIN{print length($0)}'<<<"foo"
0 #here we get 0 instead of 3, because default var in awk is "".
  #If you print NR, it is 0 as well.