Skip to content

Instantly share code, notes, and snippets.

@amalshaji
Created May 27, 2023 12:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amalshaji/bd51ed19e58f4ff7f2030477a9203ef3 to your computer and use it in GitHub Desktop.
Save amalshaji/bd51ed19e58f4ff7f2030477a9203ef3 to your computer and use it in GitHub Desktop.
Replace template file environment placeholders with values from the environment
#!/bin/bash
if [ $# -ne 2 ]; then
echo "Usage: $0 <input_file> <output_file>"
exit 1
fi
input_file=$1
output_file=$2
template=$(cat "$input_file")
while IFS= read -r -d '' match; do
variable=${match:1} # Remove the leading '$' from the match
value=${!variable} # Get the value of the environment variable
template=${template//$match/$value}
done < <(echo "$template" | grep -o '\$[A-Za-z_][A-Za-z0-9_]*' | tr '\n' '\0')
echo "$template" > "$output_file"
@amalshaji
Copy link
Author

Set the environment variables.

export TEST_ENV=env
export COLORTERM=red

Create a new file, input.txt, with contents.

test_env=$TEST_ENV
color=$COLORTERM

Run the script,

./replacer.sh input.txt output.txt

This will produce output.txt,

test_env=test
color=truecolor

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment