shell - Why using variable in awk printf doesn't work? -
newbie here. trying use awk print few information. wrote shell scripts
#!/bin/bash turbvar="u" bcname="outlet" str="$turbvar $bcname b.c. = " # method-1 awk -v rs='}' '/'$bcname'/ { printf "%20s = %s\n" $str $4; exit;}' bcfile | tr -d ";" # method-2 awk -v rs='}' -v var1=$bcname '$0 ~ var1 { printf "%20s = %s\n" $str $4; exit;}' bcfile | tr -d ";"
the bcfile
file contents are
boundary { inlet { type fixedvalue; value uniform (5 0 0); } outlet { type inletoutlet; inletvalue $internalfield; value $internalfield; } .... }
i hope output like
u outlet b.c. = inletoutlet
sadly, not work. complains awk: (filename=0/u fnr=4) fatal: not enough arguments satisfy format string %20s = %s
.
why can't use $str variable in awk printf?
second question, method better? using '/'$bcname'/
or using -v var1=$bcname '$0 ~ var1
?, why cant use '/$bcname/
or '/"$bcname"/
directly? difference between strong quote , weak quote here?
you code cleaned should be:
awk -v rs="}" -v v1="$bcname" -v s="$str" '$0~v1{gsub(/;/,"");printf "%s%s\n",s,$4;exit}' u outlet b.c. = inletoutlet
notes:
don't play shell expansion , quoting it's real headache. pass in shell variables nicely
-v
.you need comma separator arguments
printf
.always quote shell variables!
you should being doing
gsub(/;/,"")
insideawk
script instead oftr -d ";"
.
however may not best approach couldn't no context provied.
Comments
Post a Comment