如何使用一个变量在一个awk前pression [英] How to use a variable in an awk expression
问题描述
我试图使这个命令:
sed的喇嘛喇嘛名| AWK'{printf的%s%s_entry _%。3F%.3f%.3f%.3f,$ 30,$ 90,$ 4 $ 5,$ 6,$ 7}'
但事实是,我想要%.3f部分是可变的。因此,在一种情况下它可能是%.3f并在另一个可能是%.3f%.3f%.3f。所以我就用我的例子code为清楚起见静态的。所以,如果我想这些%.3f 4,把他们在变量$值,像这样:
值=%3F%.3f%.3f%.3f
然后我怎么可以把这个字符串中的AWK前pression,未做只是把awk的字面意思是$ {}值在那里。以下是我的非工作的尝试:
sed的喇嘛喇嘛名| AWK'{printf的%s%s_entry _ $ {}值,$ 30,$ 90,$ 4 $ 5,$ 6,$ 7}'
您可以用awk的 -v
选项变量传递从壳
#!/斌/庆典
AWK -v值=$ {}值'{GSUB(嗒嗒,替换); printf的%s%s_entry_的价值观....}'文件
在 GSUB()
功能是代替你有什么与 SED
命令。所以,只有一个awk命令就可以了。 SED
是多余在此情况下(以及在使用awk的其他大多数情况下)
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}'
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)
这篇关于如何使用一个变量在一个awk前pression的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!