awk - printing nth field based on parameter

I have a need to print nth field based on the parameter passed. Suppose I have 3 fields in a file, passing 1 to the function should print 1st field and so on.

I have attempted below function but this throws an error due to incorrect awk syntax.

function calcmaxlen
{
 FIELDMAXLEN=0
 POSITION=$1
 while read LINE
 do
   FIELDLEN=$(echo $LINE | awk -v POS="$POSITION" '{print \$POS}' | wc -c)
   if [ $FIELDLEN -gt $FIELDMAXLEN ]
   then
     FIELDMAXLEN=$FIELDLEN
   fi
 done <$HOME/input.dat

}
# main
#####
calcmaxlen 1
echo "Maxmimum length of field 1 is:" $FIELDMAXLEN
calcmaxlen 2
echo "Maxmimum length of field 2 is:" $FIELDMAXLEN
calcmaxlen 3
echo "Maxmimum length of field 3 is:" $FIELDMAXLEN

The ultimate objective of this function is to calculate maximum length for each field.

Awk does not use $ in variable
change $POS to POS

Hi Jotne,

But to print nth field, I need a $ prefix right? $1 prints 1st field and so on. I am passing only the field position to awk.

My fault
Remove the \
This works for me

POSITION=3
echo "test line is fine" | awk -v POS="$POSITION" '{print $POS}'
is

I believe awk does support length function..

try

function calcmaxlen
{
 awk -v POS="$1" '{if(length($POS)>max){max=length($POS)}}END{print max}' $HOME/input.dat
}
1 Like

Thanks pamu. I used the length function as you suggested and it works as expected now.