gpt4 book ai didi

awk - 如何在 awk 中使用环境变量

转载 作者:行者123 更新时间:2023-12-05 00:06:53 33 4
gpt4 key购买 nike

我有以下 AWK我用来更新的脚本 settings.py .
我在 Docker 安装期间使用,我正在尝试传递 ENV 变量。

要传递的 ENV 变量:

DB_USER,
DB_PASS,
DB_NAME

下面的代码
awk 'function pr(sp, k, v){    # prints key-value pair with indentation
printf "%s\047%s\047: \047%s\047,\n",sp,k,v;
}
/sqlite/{ sub(/sqlite[0-9]*/,"mysql",$0) }
/NAME/{ sp=substr($0,1,index($0,"\047")-1);
print sp$1" \047$DB_NAME\047";
pr(sp,"USER","$DB_USER"); pr(sp,"PASSWORD","$DB_PASS");
pr(sp,"HOST","localhost"); pr(sp,"PORT",""); next
}1'

最佳答案

您可以使用 ENVIRON GNU Awk 中的变量,
来自 GNU Awk man page ,

ENVIRON

An associative array containing the values of the environment. The array indices are the environment variable names; the elements are the values of the particular environment variables. For example, ENVIRON["HOME"] might be "/home/arnold". Changing this array does not affect the environment passed on to any programs that awk may spawn via redirection or the system() function. (In a future version of gawk, it may do so.)


使用上述数组来引用您的环境变量,只需在 BEGIN 中执行此操作即可子句加载所有变量并稍后使用
awk 'BEGIN {
db_user = ENVIRON["DB_USER"]
db_pass = ENVIRON["DB_PASS"]
db_name = ENVIRON["DB_NAME"]
}'
使用变量 db_user , db_passdb_nameAwk的正文中如你所愿。通过在 BEGIN 中导入环境变量,您不必为输入文件中的每一行导入一次。

关于awk - 如何在 awk 中使用环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46171193/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com