Last active
January 19, 2018 00:06
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
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
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 ?