如何将变量中的占位符字符或单词替换为Bash中另一个变量的值?

IAm*_*aja 32 bash shell replace

我正在尝试编写一个简单的Bash脚本.我有一个简单的"模板"变量:

template = "my*appserver"
Run Code Online (Sandbox Code Playgroud)

然后,我有一个函数(get_env())返回的值dev,qalive.我想调用get_env然后template使用get_env's返回值对变量进行字符串替换,并将其与星号交换掉.所以:

# Returns "dev"
server = get_env

# Prints "mydevappserver"
template = string_replace(server, template)
Run Code Online (Sandbox Code Playgroud)

要么:

# This time, it returns "live"
server = get_env

# Prints "myliveappserver"
template = string_replace(server, template)
Run Code Online (Sandbox Code Playgroud)

我应该用什么来代替这个string_replace()功能来完成绑定?

Spe*_*bun 63

Bash可以自行更换字符串:

template='my*appserver'
server='live'
template="${template/\*/$server}"
Run Code Online (Sandbox Code Playgroud)

有关字符串替换的更多详细信息,请参阅高级bash脚本编制指南.

所以对于bash函数:

function string_replace {
    echo "${1/\*/$2}"
}
Run Code Online (Sandbox Code Playgroud)

并使用:

template=$(string_replace "$template" "$server")
Run Code Online (Sandbox Code Playgroud)

  • 解决方案相当简单,替换ALL出现的正确形式是"$ {1 //\*/$ 2}"` (6认同)
  • 这个("$ {1 /\*/$ 2}"`仅替换脚本中的第一个出现:( (3认同)

sge*_*sge 39

bash脚本中的字符串替换可以通过sed实现:

template=$(echo $template | sed 's/old_string/new_string/g')
Run Code Online (Sandbox Code Playgroud)

这将在模板变量中用new_string替换old_string.


gni*_*urf 6

没有人提到它,这是一个很酷的可能性使用printf.占位符必须是%s,而不是*.

# 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"
Run Code Online (Sandbox Code Playgroud)

完成!

如果你想要一个函数来做(注意提到函数的所有其他解决方案如何使用丑陋的子shell):

#!/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"
Run Code Online (Sandbox Code Playgroud)

完成(再次)!

希望你喜欢它......现在,根据你的需要调整它!

备注.似乎这种方法使用printf比bash的字符串替换稍快.这里根本没有子壳!哇,这是西方最好的方法.

滑稽.如果你喜欢有趣的东西,你可以写string_replace上面的函数

string_replace() {
    printf -v "$@"
}

# but then, use as:
string_replace destination_variable "$template" "$server"
Run Code Online (Sandbox Code Playgroud)