largest field , awk , help

Hi All,

My file is like this:

$ cat max.txt
abcd:1982:a
efghij:1980:e
klmn:1923:k
opqrst:1982:o

I have to find out the largest first field and the corresponding line. i.e

Output required:

efghij efghij:1980:e
opqrst opqrst:1982:o

HTH,
jkl_jkl

try this code:

#!/bin/bash

#constant
INFILE="max.txt"

#core script
awk ' BEGIN { OFS=FS=":"; cur=max=0; seen=""}
        {
           cur = length($1)
           if(cur > max ){
              seen = $1 " " $0
           }
           else if(cur == max){
              seen = seen "\n"  $1 " " $0
           }
        }
        END { print seen }'  $INFILE
#exit normally
exit 0

.Aaron

aaron,

It prints only

opqrst opqrst:1982:o

And not

efghij efghij:1980:e
opqrst opqrst:1982:o

i.e. if there are 2 longest fields, its printing the last one.

Just add "max=cur" and both lines are printed out as you want.

awk ' BEGIN { OFS=FS=":"; cur=max=0; seen=""}
        {
           cur = length($1)
           if (cur > max ) {
              seen = $1 " " $0
              max = cur
           } else if (cur == max) {
              seen = seen "\n"  $1 " " $0
           }
        }
        END { print seen }'  $INFILE

Another sol:

awk '{l=length($1);if(l>=max){a[$1" "$0]=l;max=l}}END{for(i in a)if (a==max)print i}' FS=':' file

ohsorry, I forgot the "max =cur", when I input my code into the reply!

.Aaron

Hi i was wondering how you would do the opposite meaning find the lowest field and the corresponding line?

thanks in advance.