awk 命令接受两个变量作为参数并返回一个值
我有一个有 50 行的文件。每行由三列组成。前两列是变量,这将作为参数传递以返回第三列的值。 对于前.. command_file.txt 是文件,它包含
A B 10 C D 20 E F 30 G H 50 I J 70 ...
我有一个包含以下命令的脚本。
#!/user/bin/sh READ_FILE=/export/home/user/command_file.txt VA1=A VA2=B GET_VALUE=`awk '/ -v var="$VA1" '$1 ~ var' -v var1="$VA2" '$1 ~ var1''/ $READ_FILE l awk '{print $3}'` echo $GET_VALUE
当我调用此脚本并传递 A 和 B 作为参数时,我期望返回值 10。但它返回了错误。 但如果我对以下命令的值进行硬编码,它将起作用。
GET_VALUE=`awk '/A B'/ $READ_FILE lawk '{print $3}'`
有什么建议吗? 谢谢。
I have a file which has 50 rows. Each row is made up of three columns. The first two columns are the variables and this will be passed as parameters to return the 3rd column's value.
for ex..
command_file.txt is the file and it contains
A B 10 C D 20 E F 30 G H 50 I J 70 ...
I have a script with the following command.
#!/user/bin/sh READ_FILE=/export/home/user/command_file.txt VA1=A VA2=B GET_VALUE=`awk '/ -v var="$VA1" '$1 ~ var' -v var1="$VA2" '$1 ~ var1''/ $READ_FILE l awk '{print $3}'` echo $GET_VALUE
When I call this script passing A and B as parameters I expect a value of 10 to be returned.But it returned errors.
But if I hard code the value on the below command it will work.
GET_VALUE=`awk '/A B'/ $READ_FILE lawk '{print $3}'`
Any suggestions?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在 awk 脚本开始之前,您必须使用 awk 的变量传递以避免毛茸茸的引用,并修复其他问题:
You have to use
awk's
variable passing before the awk script begins to avoid hairy quoting, plus fix other problems:很抱歉,我无法真正确定您的脚本想要做什么,因此我无法正确调试它。我想也许你嵌套了引号或者发生了其他事情。
我认为下面的一行可以满足您的要求。
编辑
好的,感谢其他人指出您尝试使用 -v 选项执行的操作。
您的代码在 echo GET_VALUE 命令上缺少 $,并且有字母 l 而不是管道 |。另外,还有其他错别字。
我认为这可行
,但我更喜欢上面的 grep 命令,因为它不需要额外的努力将命令行变量传递给 awk。
I apologize that I can't really determine what your script is trying to do, so I can't debug it properly. I think maybe you have nested quotes or something else is going on.
I think the one-liner below will do what you want.
Edit
Okay thanks to others for pointing out what you were trying to do with the -v options.
Your code is missing a $ on the echo GET_VALUE command, and you have a letter l instead of a pipe |. Plus there are other typos as well.
I think this works
but I prefer the grep command above as it requires no extra effort to pass the command line variables to awk.
我认为这就是您正在寻找的:
I think this is what you're looking for:
或者也许:
如果您的变量需要按任一顺序?
Or perhaps:
If your vars need to be in either order?
固定的:
Fixed:
我知道这是一篇旧帖子,但 awk 更旧并且仍在使用 - 人们仍在寻找相同的答案。我想我就是这方面的一个例子。
我决定实现一个类似的场景,但希望在配置文件中预定义变量。用户将配置文件的部分名称作为第一个参数传递给脚本。
I know this is an old post but awk is even older and still in use - and people are still looking for the same answers. I suppose I was an example of this.
I decided to implement a similar scenario but wanted predefined variables in the config file. The user passes the partial name of config file to script as first parameter.