showkey
showkey

Reputation: 358

How to use the max number for every 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 ?

Upvotes: 1

Views: 903

Answers (2)

Dariusz Wawrzyniak
Dariusz Wawrzyniak

Reputation: 21

You can read your file line by line by means of getline. If you use it in your BEGIN block and repeat as long as it returns 1, you can process the whole input stream. Add this line before your if statement:

while ( getline > 0 )

The whole script looks as follows:

BEGIN {max =0
    while ( getline > 0 )  
       if (length($0) > max) { max = length($0)}
    print max}

Upvotes: 0

Kent
Kent

Reputation: 195079

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.

E.g.

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.

Upvotes: 2

Related Questions