How to replace placeholder character or word in variable with value from another variable in Bash? How to replace placeholder character or word in variable with value from another variable in Bash? bash bash

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")


String replacement in a bash-script can e.g. be achieved by sed:

template=$(echo $template | sed 's/old_string/new_string/g')

This will replace old_string with new_string in the template variable.


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"