Skip to content

Instantly share code, notes, and snippets.

@niclashoyer
Last active January 19, 2018 00:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niclashoyer/8146033 to your computer and use it in GitHub Desktop.
Save niclashoyer/8146033 to your computer and use it in GitHub Desktop.
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
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
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