How to use a variable in awk expression

I am trying to make this command:

sed bla bla filename | awk '{printf "%s %s_entry_%.3f %.3f %.3f %.3f",$1,$3,$4,$5,$6,$7}'

But the fact is, I want the% .3f part to be variable. Thus, in one case it can be% .3f, and in another -%. 3f% .3f% .3f. Therefore, I just use static code in my code example for clarity. Therefore, if I want 4 of these% .3f and put them in $ variable variables like this:

values="%.3f %.3f %.3f %.3f"

Then how can I put this line in an awk expression without making awk just put literally "$ {values}" there. The following is my non-working attempt:

sed bla bla filename | awk '{printf "%s %s_entry_${values}",$1,$3,$4,$5,$6,$7}'
+3
source share
3 answers

you can use the -vawk option to pass a variable from the shell

#!/bin/bash    
awk -v values="${values}" '{gsub("blah","replace");printf "%s %s_entry_"values ....}' file

gsub() , sed. awk. sed ( , awk)

+6

awk:

sed bla bla filename | awk -v values="$values" '{printf "%s %s_entry_"values,$1,$3,$4,$5,$6,$7}'

bash:

awk -v values="$values" '{printf "%s %s_entry_"values,$1,$3,$4,$5,$6,$7}' <(sed bla bla filename)
+2

If you mean that valuesis a shell variable, then this will work:

sed bla bla filename | awk '{printf "%s %s_entry_"ENVIRON["values"],$1,$3,$4,$5,$6,$7}'
+1
source

Source: https://habr.com/ru/post/1740298/


All Articles