我有以下代码将ENV变量传递给AWK。
awk 'function pr(sp, k, v){ # prints key-value pair with indentation
printf "%s\047%s\047: \047%s\047,\n",sp,k,v;
}
BEGIN {
db_user = ENVIRON["DB_USER"]
db_pass = ENVIRON["DB_PASS"]
db_name = ENVIRON["DB_NAME"]
}
/sqlite/{ sub(/sqlite[0-9]*/,"mysql",$0) }
/NAME/{ sp=substr($0,1,index($0,"\047")-1);
print sp$1" \047db_name\047,";
pr(sp,"USER", db_user); pr(sp,"PASSWORD", db_pass);
pr(sp,"HOST","localhost"); pr(sp,"PORT",""); next
}1'
我可以用ENV变量替换db_name。
db_name = django
我的结果是:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'db_name',
'USER': 'django',
'PASSWORD': 'django',
'HOST': 'localhost',
'PORT': '',
}
}
答案 0 :(得分:1)
print
中Awk
语句的不正确使用问题。从此GNU Awk print()
页面可以看出,您需要将变量移到引号之外以查看其扩展值。
print sp$1" \047db_name\047,";
# ^^^^^^^ Awk does not understand db_name within quotes
只需将其置于引号之外,如下所示。
print sp$1" \047"db_name"\047,"
(或)完全使用printf
将格式说明符与变量分开,并执行以下操作
printf "%s %s \047%s\047,\n",sp,$1,db_name