awk linux shell变量调用shell变量
这可能是一个简单的/什么,这个问题是:在这里,我加载4个变量$ 1 $ 2 $ 3和$ 4 说
file1
1 2 3
1 4 5
1 6 7
myloop () {
echo col=$1 $2 $3 $4
awk -v c1="$1" -v c2="$2" -F, 'BEGIN {
FS=" ";
}
{
xy+=($c1*$c2);
}
END {
print "Product" $3 "and " $4 #this is where $3 (='h2') and $4 (='02') don't print
print "prod= " xy;
}' file1 > res.txt
}
myloop 2 3 h2 o2
res.txt中的预期输出,
product h2 and 02
prod = 68
因此,正如我在代码中注释的行中所说的那样,我无法阅读3美元和4美元。
我尝试通过$ 3和$ 4的awk -v c1 =“ $ 1” -v c2 =“ $ 2” -vl1 =“ $ 3” -v l2 =“ $ 4” ...
,然后在打印语句中调用$ l1和$ l2但这不起作用。
任何提示都将不胜感激,因为我不是脚本的专家(您可以告诉)
提前致谢
this is probably an easy/what-the-hell-is-that question: here a blueprint of the script where I load 4 variables $1 $2 $3 and $4 in a function 'myloop'
say
file1
1 2 3
1 4 5
1 6 7
myloop () {
echo col=$1 $2 $3 $4
awk -v c1="$1" -v c2="$2" -F, 'BEGIN {
FS=" ";
}
{
xy+=($c1*$c2);
}
END {
print "Product" $3 "and " $4 #this is where $3 (='h2') and $4 (='02') don't print
print "prod= " xy;
}' file1 > res.txt
}
myloop 2 3 h2 o2
expected output in res.txt
product h2 and 02
prod = 68
so as I said in the commented line in the code, I can't get to read $3 and $4.
I try passing $3 and $4 withawk -v c1="$1" -v c2="$2" -vl1="$3" -v l2="$4" ...
and then call $l1 and $l2 in the print statement but that does not work.
any hint would be appreciated as I'm no expert (as you can tell) in scripting
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您要寻找的称为字符串插值,可以像这样执行:
What you are looking for is called string interpolation and can be performed like so:
l1
和l2
是变量名的错误选择,因为l
在许多字体中看起来太像1
因此,使您的代码混淆。顺便说一句,在您的问题中,此:
将fs从空白的默认值更改为逗号,然后将其更改为:
将其设置回其必须开始的默认空白值。只是不要那样做。
l1
andl2
are bad choices for variable names though sincel
looks far too much like1
in many fonts and so obfuscates your code.By the way, in your code in your question, this:
is changing FS from it's default value of a blank to a comma and then this:
is setting it back to the default blank value it had to begin with. Just don't do that.