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 |
This comment has been minimized.
This comment has been minimized.
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
This comment has been minimized.
bortek commentedNov 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 ?