Created
November 24, 2016 14:40
-
-
Save ticklemynausea/e67e46647b541080b2e82e5c4cfc1320 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
| # | |
| # replace.sh | |
| # | |
| # Replace template-like sequences in text files with the value of similarly named environment | |
| # variables that the script knows about. | |
| # | |
| # For example, for a file named test.txt with the contents `{{HOME}} is where the {{THING}} is`, | |
| # running `THING=heart replace.sh . test.txt` would transform the contents of the file into | |
| # `/home/youruser is where the heart is`. | |
| # | |
| # The script always runs recursively from the given directory. | |
| # | |
| # Variables can be passed to the script right before execution or pre-defined in the | |
| # environment. | |
| # | |
| # | |
| # script usage info (when arguments are wrong or missing) | |
| function usage() { | |
| echo "Usage: [environment] $0 <directory> <glob>" 1>&2 | |
| echo "Example: VAR1=VAL1 VAR2=VAL2 $0 my-conf-directory '*.conf'" 1>&2 | |
| exit -1 | |
| } | |
| # | |
| # find sequences like {{SOMETHING}} in files that match GLOBPATTERN in the given DIRECTORY | |
| function get_variables() { | |
| for line in `grep -hroP --include=$GLOBPATTERN '{{(\S+)}}' $DIRECTORY | sort | uniq` | |
| do | |
| if [[ $line =~ \{\{(.+)\}\} ]] | |
| then | |
| echo ${BASH_REMATCH[1]}; | |
| fi | |
| done | |
| } | |
| # | |
| # $1: directory to recurse under | |
| # $2: glob pattern to match files | |
| # | |
| DIRECTORY=$1 | |
| GLOBPATTERN=$2 | |
| # | |
| # if either is not given, don't run | |
| [[ -z $DIRECTORY ]] && usage | |
| [[ -z $GLOBPATTERN ]] && usage | |
| # | |
| # perform replacements | |
| for v in `get_variables` | |
| do | |
| if [[ -n ${!v} ]] | |
| then | |
| echo "Replacing '{{$v}}' with ${!v}" | |
| find $DIRECTORY -type f -name $GLOBPATTERN -exec sed -i -e "s|{{$v}}|${!v}|g" {} \; | |
| fi | |
| done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment