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

后端 未结 8 2112
死守一世寂寞
死守一世寂寞 2020-12-08 14:01

I\'m trying to write a simple Bash script. I have a simple \"template\" variable:

template = \"my*appserver\"

I then have a function (

8条回答
  •  没有蜡笔的小新
    2020-12-08 14:21

    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-holder
    template="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_name
    string_replace() {
        printf -v $3 "$2" "$1"
    }
    
    # How to use it:
    template="my%sappserver"
    server="whatever-you-like"
    
    string_replace "$server" "$template" destination_variable
    
    echo "$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"
    

提交回复
热议问题