If awk statement doesn't work as predicted

My values โ€‹โ€‹of the second column start from 0 to 2000, and the variable $ a is set to 13. If the instruction in awk does not work as intended ... it prints all the values. The code:

#!/bin/sh
IFS=- read a b <<< "$1"
echo $a # value is displayed as 13
echo $b # value is displayed as 20... for now it does not matter
sort -r -k 2,2 $2 | awk '{if ($2 > $a) print $2}'  # if statement should check which of a second column values are greater than 13, and print them 

Everything is fine when I compare my second column like this (putting 13 instead of $ a):

 sort -r -k 2,2 $2 | awk '{if ($2 > 13) print $2}'

So my thought is that I put the wrong argument $ a in

+4
source share
2 answers

This is because shell variables will not expand with single quotes.

awk has a convenient mechanism for setting awk variables:

awk -v value="$a" '{if ($2 > value) print $2}'

which can be written "awkishly" as

awk -v value="$a" '$2 > value {print $2}'
+2
source
awk  -v var="$a" '{if ($2 > var)print $2}'

. awk. -v awk-.

. Awk $, bash, / (, $1, $2 ..).

+2

All Articles