AWK - fields to variables

February 18, 2010 at 11:29:42
Specs: AIX
Does anyone know how to set multiple variables from different fields in awk?

I am running the following 2 lines of code in a loop over 16,000 times. I would like to see if combining this into a one liner would be faster

JOB=$(awk "NR == ${jobline} {print;exit}" "$TMPDIR/$JOBFILE2" |awk '{print $1}')
APPL=$(awk "NR == ${jobline} {print;exit}" "$TMPDIR/$JOBFILE2" |awk '{print $2}')

I want to set the JOB and APPL variable with $1 and $2 of the file, all in 1 awk command - possible?

Thanks!


See More: AWK - fields to variables

Report •

#1
February 18, 2010 at 20:56:45
Since efficiency is an issue, you can modify this line:

JOB=$(awk "NR == ${jobline} {print;exit}" "$TMPDIR/$JOBFILE2" |awk '{print $1}')

and eliminate piping to the second awk call:

jobline=2
JOB=$(awk ' { if(NR == v1) {print $1 ;exit} } ' v1=$jobline $TMPDIR/$JOBFILE2)

One way of combining the two awk statements into one is to print field one and field two with a pipe sybmol. Capture that output to variable myvar. Then, using the set command, parse myvar into arguments $1 and $2:

jobline=2
myvar=$(awk ' { if(NR == v1) {printf("%s|%s", $1, $2) ;exit} } ' v1=$jobline $TMPDIR/$JOBFILE2)

set - $(IFS="|"; echo $myvar)
JOB="$1"
APPL="$2"


Report •
Related Solutions


Ask Question