Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using bash variables inside awk

Tags:

bash

awk

Trying to pass the external "CLIENT_ID" variable into this line of awk, but it doesn't work as expected. This is what I've tried:

CLIENT_ID=1
awk -v CLIENT_ID="${CLIENT_ID}" 'NF{print "xxx_${CLIENT_ID}_" $0 ".sh"}' A.csv > B.csv

in A.csv

201712
201711
201710

Desired output in B.csv:

xxx_1_201712.sh
xxx_1_201711.sh
xxx_1_201710.sh

What I'm currently getting:

xxx_${CLIENT_ID}_201712.sh
xxx_${CLIENT_ID}_201711.sh
xxx_${CLIENT_ID}_201710.sh
like image 892
Chubaka Avatar asked Sep 25 '17 22:09

Chubaka


People also ask

How do you pass variables from awk to shell?

Passing variables from 'awk' to the shell (its parent process) can be done by 'eval'ing the 'awk' (or an entire pipleline ending with an 'awk' if desired), and having the 'awk' print text which will cause its parent shell to put the information you want into variables.

What is awk '{ print $1 }'?

awk '{print $1}' information. txt prints the first column. Then the output of that command (which you saw earlier on) is piped, using the pipe symbol | , to the head command, where its -1 argument selects the first line of the column. If you wanted two lines printed, you'd do: awk '{print $1}' information.txt | head -2.


1 Answers

${CLIENT_ID} is bash syntax. You should instead use the awk syntax you're already using for $0:

awk -v CLIENT_ID="${CLIENT_ID}" 'NF{print "xxx_" CLIENT_ID "_" $0 ".sh"}' A.csv > B.csv
like image 130
that other guy Avatar answered Oct 01 '22 23:10

that other guy