bash AWK:将值返回给 shell 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9708028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:47:14  来源:igfitidea点击:

AWK: return value to shell script

bashawk

提问by Shuvo Shams

Is it possible to have an awk command within a bash script return values to a bash variable, i.e.,if my awk script does some arithmetic operations, can I store the answers in variables so, they can be accessed in the bash script. If possible, how to distinguish between multiple return variables. Thanks.

是否可以在 bash 脚本中使用 awk 命令将值返回给 bash 变量,即,如果我的 awk 脚本执行一些算术运算,我可以将答案存储在变量中,以便可以在 bash 脚本中访问它们。如果可能,如何区分多个返回变量。谢谢。

回答by Eduardo Ivanec

No. You can use exitto return an error code, but in general you can't modify the shell environment from a subprocess.

不可以。您可以使用exit返回错误代码,但通常您不能从子进程修改shell 环境。

You can also, of course, print the desired content in awk and put it into variables in bash by using read:

当然,您也可以在 awk 中打印所需的内容,然后使用以下命令将其放入 bash 中的变量中read

read a b c <<< $(echo "foo" | awk '{ print ; print ; print  }')

Now $a, $band $care all 'foo'. Note that you have to use the <<<$()syntax to get read to work. If you use a pipeline of any sort a subprocess is created too and the environment readcreates the variables in is lost when the pipeline is done executing.

现在$a$b$c都是'foo'。请注意,您必须使用<<<$()语法才能读取工作。如果您使用任何类型的管道,也会创建一个子进程,并且read当管道完成执行时,环境创建的变量将丢失。

回答by Jake Nicholson

var=$(awk '{ print }')

This should set var to the output of awk. Then you can use string functions or whatever from there to differentiate within the value or have awk print only the part you want.

这应该将 var 设置为 awk 的输出。然后你可以使用字符串函数或其他任何东西来区分值或让 awk 只打印你想要的部分。