Ankh2054
Ankh2054

Reputation: 1153

AWK passing ENV variables

I have the following code to pass ENV variables to 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'

I can get the db_name to be replaced with the ENV variable.

db_name = django

My results are:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'db_name',
        'USER': 'django',
        'PASSWORD': 'django',
        'HOST': 'localhost',
        'PORT': '',
      }
}

Upvotes: 1

Views: 306

Answers (1)

Inian
Inian

Reputation: 85800

The problem is incorrect use of print statement in Awk. As seen from this GNU Awk print() page, you need to move the variable outside the quotes to see its expanded value.

print sp$1" \047db_name\047,"; 
#               ^^^^^^^ Awk does not understand db_name  within quotes

Just make it outside the quotes as below.

print sp$1" \047"db_name"\047,"

(or) Use printf altogether to separate the format specifiers from the variables and do as below

printf "%s %s \047%s\047,\n",sp,$1,db_name 

Upvotes: 2

Related Questions