views:

44

answers:

3

I'm 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 thing is, i want the %.3f part to be variable. So in one case it could be %.3f and in another it could be %.3f %.3f %.3f. So i'll just use a static one in my example code for clarity. So if i want 4 of these %.3f and put them in variable $values like so:

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

Then how can i put this string in the awk expression, without making awk to just put literally "${values}" in there. The following is my non-working-attempt:

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

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

sed bla bla filename | awk '{printf "%s %s_entry_"ENVIRON["values"],$1,$3,$4,$5,$6,$7}'
Marcelo Cantos
Thnx for the reply, +1!
lugte098
That only works if you `export values` or `values=something awk ...`
Dennis Williamson
Or if you write `values=... awk '...'`. But still, good point.
Marcelo Cantos
+1  A: 

Easiest to use actual awk variables:

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

Or with bash:

awk -v values="$values" '{printf "%s %s_entry_"values,$1,$3,$4,$5,$6,$7}' <(sed bla bla filename)
Ignacio Vazquez-Abrams
Thnx for the reply, +1!
lugte098
+2  A: 

you can use -v option of awk to pass in variable from the shell

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

the gsub() function is to replace what you have with that sed command. So just one awk command will do. sed is redundant in this case (and most other cases where awk is used)

ghostdog74
Thnx, just using awk -v values="${values}" worked like a charm! +1 and accept for you!
lugte098