I'm having an issue getting variable assignment to work in a script I've written that uses awk
. The awk
command sits inside of a function and there are three variables that are passed to that function elsewhere in the script. I made this work previously by breaking the awk
command with the variable: awk ... '"$var"' ...
, but apparently this is a rather sloppy way of doing it, and awk
allows variable assignemnt via the -v
switch.
This is what I'm trying to do:
my_function() {
command1 \
| command2 \
| awk -v var1="$1" -v var2="$2" -v var3="$3" '{
FS="[ ,\"]+"}/var1=/{
for ( i=2; i<NF; i++) {
if ( var2 ){
var3; next;
}
}
}
{
fname=$0
}'
}
...
my_function "$firstArg" "$secondArg" "$thirdArg"
Based on the output from using set -x
, I can see that the variable assignment are made properly in the beginning of the awk command, but the awk
command simply returns nothing as oppossed to doing it the awk ... '"$var"' ...
way, which does work properly.
I feel like I'm just missing something here.
/var1=/
is a regexp constant - if you want to use a variable in a regex test, you'd need to do it like$0 ~ var1"="
. See Pass shell variable as a /pattern/ to awk – steeldriver Aug 17 '21 at 01:57This is what I'm trying to do:
- no, that's a block of code that doesn't do whatever it is you're trying to do. We can't tell what you're really trying to do by reading code that doesn't do what you want, you'd have to specifically tell us what you're trying to do and provide some sample input/output to demonstrate it for us to be able to fully help you. – Ed Morton Aug 17 '21 at 15:54