python - How can I process variable substitutions in bash? -
so have files contain placeholder values @user@
or @shell@
(all-caps variable names, enclosed in @'s, representing environment variable names). want replace placeholders actual values of environment varables reference.
in past when i've seen sort of thing done, specific variables hard-coded, eg:
sed -e 's/@some_variable@/$some_value/' <infile >outfile
but won't work current use-case want more flexibly support arbitrary substitutions. wrote code in python want:
import re import fileinput os import environ sys import stdout pat = re.compile(r'@([a-z_]+)@') line in fileinput.input(): stdout.write(pat.sub(lambda match: environ[match.group(1)], line))
but i'd prefer not use python if can it. surely there's way perl or sed one-liner?
perl -pe 's/\@(\w+)\@/$env{$1}/g'
1 way job.
if want throw error if variable mentioned in file doesn't exist in environment, use
perl -pe 's/\@(\w+)\@/die "$1 not found\n" unless exists $env{$1}; $env{$1}/eg'
Comments
Post a Comment