Skip to content

Instantly share code, notes, and snippets.

@niclashoyer niclashoyer/cpconfig.sh
Last active Jan 19, 2018

Embed
What would you like to do?
Replace environment variables in configuration files with optional default using perl regular expressions.
#!/bin/bash
#
# Replaces ${var:def} expressions in text files with environment variables with
# an optional default.
#
# Assuming VAR1 contains the value "foo" nad VAR2 is undefined, the following
# expressions will evaluate as given on the right side:
#
# ${VAR1} ~> foo
# ${VAR2:bar} ~> bar
# ${VAR1:bar} ~> foo
# ${VAR2} ~> (empty string)
#
perl -p -e 's/\$\{([^}:]+)(:([^}:]+))?\}/defined $ENV{$1} ? $ENV{$1} : $3/eg' $1
@bortek

This comment has been minimized.

Copy link

bortek commented Nov 22, 2017

How can one remake this one liner to NOT do substitution on variables which are empty or not defined and leaving them as e.g. ${VAR66} in the input file ?

@bortek

This comment has been minimized.

Copy link

bortek commented Nov 22, 2017

I found this which does exactly what I want

perl -wpne 's#${?(\w+)}?# $ENV{$1} // $& #ge;' inputfile.txt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.