Skip to content

Instantly share code, notes, and snippets.

@magnetikonline
Last active June 15, 2018 22:33
Show Gist options
  • Save magnetikonline/5e8cf545034fb81bf6c3 to your computer and use it in GitHub Desktop.
Save magnetikonline/5e8cf545034fb81bf6c3 to your computer and use it in GitHub Desktop.
Escaping token replace values for sed.

Escaping token replace values for sed

In this case replacement is passed in $1. Will replace TOKEN_NAME in given /path/to/my/templatefile.txt.

The magic is sed --regexp-extended 's/[\/&]/\\&/g' - ensures replace value is not tripped up in call to sed.

#!/bin/bash -e

tokenReplace=$1

cat /path/to/my/templatefile.txt | \
	sed --regexp-extended "s/TOKEN_NAME/$(echo "$tokenReplace" | sed --regexp-extended 's/[\/&]/\\&/g')/" \
	>/path/to/output.txt

Reference

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