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.