1

This question already has an answer here:

I have around 1000 files where on each of them if the first field matches a specific number , i need to print the corresponding 3rd element . Since the number 7 below, is not constant and it based upon the output of previous script , when I am trying to pass a variable , it fails .

$cat ${i} | head -14 | awk '$1 == "7" {print $3}'
$Supervisor
$blah=7
$cat ${i} | head -14 | awk '$1 == "${blah}" {print $8}'

I have tried looking around with other combinations to escape/expand the variable inside the comparison , none of them seem to be able to expand the variable blah.

marked as duplicate by steeldriver, Jeff Schaller, sam, Kusalananda, mdpc Jan 27 '17 at 0:10

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 2
    The shell variable is not being substituted because your awk scripts is inside single quotes. – glenn jackman Jan 26 '17 at 19:31
5

Your best bet is probably to pass it as an awk variable with -v

head -14 "$i" | awk -v blah="$blah" '$1 == blah {print $8}'

or without the head part:

awk -v blah="$blah" 'NR > 14 {exit} $1 == blah {print $8}' "$i"

Not the answer you're looking for? Browse other questions tagged or ask your own question.