The previous answer also works as a function, I'm just lacking reputation to answer with a comment there.
VAR=anything
function escape() { printf '%s\n' "$1" | LC_ALL=C sed 's|[+/&\\]|\\&|g;$!s/$/\\/' }
LC_ALL=C sed -E -e "s/^(hostname=).*/\1$(escape $VAR)/" -i -- "$file"
Please note that I have amended the +
character to the escape rule.
This also works nicely with dynamically provided VAR
or otherwise provided substitution values.
LC_ALL=C sed -E -e "s/^(> API_SECRET=).*/\1$(escape $(pwgen -n 64 1))/" -i -- diff.patch
VAR="admin"; LC_ALL=C sed -E -e "s/^(+SP_ADMIN_USER=).*/\1$(escape "${VAR}")/" -i diff.patch
The command differs from the original example by omitting a possibly redundant -e
and also --
.
It's possible to further parametrise this logic with another function, omitting VAR
altogether.
function replace() { LC_ALL=C sed -E -e "s/^($(escape "${1}")).*/\1$(escape "${2}")/" -i "${3}" }
replace "+ADMIN_USER=" "admin" diff.patch
It could then be used programmatically to replace values after chosen line beginnings.
-i
option takes an argument, which will be used as a backup suffix. You are usingre
as the backup suffix. This is a typo. You also escape the$
on your variable, so it's value won't be inserted. – Kusalananda Dec 16 '19 at 09:06