How to replace placeholder character or word in variable with value from another variable in Bash?
Bash can do string replacement by itself:
template='my*appserver'server='live'template="${template/\*/$server}"
See the advanced bash scripting guide for more details on string replacement.
So for a bash function:
function string_replace { echo "${1/\*/$2}"}
And to use:
template=$(string_replace "$template" "$server")
As nobody mentioned it, here's a cool possibility using printf
. The place-holder must be %s
though, and not *
.
# use %s as the place-holdertemplate="my%sappserver"# replace the place-holder by 'whatever-you-like':server="whatever-you-like"printf -v template "$template" "$server"
Done!
If you want a function to do that (and notice how all the other solutions mentioning a function use an ugly subshell):
#!/bin/bash# This wonderful function should be called thus:# string_replace "replacement string" "$placeholder_string" variable_namestring_replace() { printf -v $3 "$2" "$1"}# How to use it:template="my%sappserver"server="whatever-you-like"string_replace "$server" "$template" destination_variableecho "$destination_variable"
Done (again)!
Hope you enjoyed it... now, adapt it to your needs!
Remark. It seems that this method using printf
is slightly faster than bash's string substitution. And there's no subshell at all here! Wow, that's the best method in the West.
Funny. If you like funny stuff you could write the function string_replace
above as
string_replace() { printf -v "$@"}# but then, use as:string_replace destination_variable "$template" "$server"