从目前的awk shell设置变量 [英] Set variable in current shell from awk

查看:171
本文介绍了从目前的awk shell设置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从内部 AWK

设置一个变量在我目前的shell

我想对一个文件进行一些处理,并打印出一些数据;因为我将通过读取整个文件,我要保存的行数 - 在这种情况下, FNR

但偏偏我似乎无法找到一种方法来设置与 FNR 值一个shell变量;如果不是这样,我不得不读 FNR 从我的输出文件,设置,比如 NUM_LINES ,与 FNR 值。

我已经使用的awk'END {系统(...)} 尝试了一些组合,但不能管理它的工作。解决这个办法?


解决方案

  $回声$ VAR$ $申报(AWK'BEGIN {打印VAR = 17})
$回声$ VAR
17

这也是为什么你应该使用声明,而不是EVAL:

  $ $的eval(AWK'BEGIN {打印回声\\删除所有文件,哈哈哈.... \\}')
删除所有文件,哈哈哈....$ $申报(AWK'BEGIN {打印回声\\删除所有文件\\}')
庆典:宣布:'删除':不是一个有效的标识符
庆典:声明:`文件':不是有效的标识符

请注意在EVAL执行时的任何字符串AWK打印第一种情况下,这可能会意外地是一个非常糟糕的事情!

Is there a way to set a variable in my current shell from within awk?

I'd like to do some processing on a file and print out some data; since I'll read the whole file through, I'd like to save the number of lines -- in this case, FNR.

Happens though I can't seem to find a way to set a shell variable with FNR value; if not this, I'd have to read the FNR from my output file, to set, say num_lines, with FNR value.

I've tried some combinations using awk 'END{system(...)}', but could not manage it to work. Any way around this?

解决方案

$ echo "$var"

$ declare $( awk 'BEGIN{print "var=17"}' )
$ echo "$var"
17

Here's why you should use declare instead of eval:

$ eval $( awk 'BEGIN{print "echo \"removing all of your files, ha ha ha....\""}' )
removing all of your files, ha ha ha....

$ declare $( awk 'BEGIN{print "echo \"removing all of your files\""}' )
bash: declare: `"removing': not a valid identifier
bash: declare: `files"': not a valid identifier

Note in the first case that eval executes whatever string awk prints, which could accidentally be a very bad thing!

这篇关于从目前的awk shell设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆