JJ Yeo JJ Yeo - 6 months ago 18
Bash Question

Unable to pass shell variables into awk

I am trying to get data between sequences of numbers, for instance:

100000000
1 2 3 4
5 6 7 8
....
100001000
....
200000000


I match the patterns using awk and I can use it successfully without using variables, for instance:

awk '/10000000 /{flag=1;next}/10001000/{exit}flag' input.dat


However when I try to use shell variables within this command, it gives no output whatsoever:

for i in {1..4}
do
step1=$(($i*10000000))
step2=$(($step1+1000))
awk -v arg1="$step1" -v arg2="$step2" '/arg1 /{flag=1;next}/arg2 /{exit}flag' input.dat

done


Is there something obvious I'm missing?

Answer

Regex literal /.../ doesn't allow variables. You can use ~ operator for regex matching in regex with variables:

 awk -v arg1="$step1" -v arg2="$step2" '$0 ~ arg1 " "{flag=1; next}
      $0 ~ arg2{exit} flag' input.dat 
Comments