停止AWK覆盖文件中的下一部分

时间:2017-09-12 12:06:26

标签: awk

我有以下更新settings.py文件的AWK脚本。

原始settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

这是更新DATABASE部分的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" \047" db_name "\047,"; 
             pr(sp,"USER", db_user); pr(sp,"PASSWORD", db_pass); 
             pr(sp,"HOST","localhost"); pr(sp,"PORT",""); next 
     }1'

在AWK脚本之后输出新的settings.py,这也是更新下面的AUTH部分。

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


# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django',
        'USER': 'django',
        'PASSWORD': 'django',
        'HOST': 'localhost',
        'PORT': '',
    },

如何阻止AWK覆盖AUTH部分?

2 个答案:

答案 0 :(得分:1)

应用以下更新:

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"]
    }
     /DATABASES/{ f=1 }/AUTH_PASSWORD_VALIDATORS/{ f=0 }
     /sqlite/{ sub(/sqlite[0-9]*/,"mysql",$0) }
     /NAME/ && f{ 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' settings.py

答案 1 :(得分:1)

小修改可以解决您的问题

/AUTH_PASSWORD_VALIDATORS/{ auth=1 }
!auth && /NAME/{