Skip to content

Instantly share code, notes, and snippets.

@niclashoyer
Last active January 19, 2018 00:06
Show Gist options
  • 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

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