如何用 Bash 中另一个变量的值替换变量中的占位符字符或单词?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13710806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to replace placeholder character or word in variable with value from another variable in Bash?
提问by IAmYourFaja
I'm trying to write a simple Bash script. I have a simple "template" variable:
我正在尝试编写一个简单的 Bash 脚本。我有一个简单的“模板”变量:
template = "my*appserver"
I then have a function (get_env()
) that returns the values dev
, qa
, or live
. I'd like to call get_env
and then string-replace the template
variable with get_env
's return value and swap it out with the asterisk. So:
然后我有一个函数 ( get_env()
) 返回值dev
、qa
、 或live
。我想调用get_env
,然后template
用get_env
的返回值字符串替换变量,并用星号替换它。所以:
# Returns "dev"
server = get_env
# Prints "mydevappserver"
template = string_replace(server, template)
Or:
或者:
# This time, it returns "live"
server = get_env
# Prints "myliveappserver"
template = string_replace(server, template)
What should I be using in lieu of this string_replace()
function to accomplish the binding?
我应该用什么来代替这个string_replace()
函数来完成绑定?
回答by Spencer Rathbun
Bash can do string replacement by itself:
Bash 可以自己进行字符串替换:
template='my*appserver'
server='live'
template="${template/\*/$server}"
See the advanced bash scripting guidefor more details on string replacement.
有关字符串替换的更多详细信息,请参阅高级 bash 脚本指南。
So for a bash function:
所以对于 bash 函数:
function string_replace {
echo "${1/\*/}"
}
And to use:
并使用:
template=$(string_replace "$template" "$server")
回答by sge
String replacement in a bash-script can e.g. be achieved by sed:
例如,可以通过 sed 实现 bash 脚本中的字符串替换:
template=$(echo $template | sed 's/old_string/new_string/g')
This will replace old_string with new_string in the template variable.
这将在模板变量中用 new_string 替换 old_string。
回答by gniourf_gniourf
As nobody mentioned it, here's a cool possibility using printf
. The place-holder must be %s
though, and not *
.
正如没有人提到的那样,这是一个很酷的可能性,使用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"
Done!
完毕!
If you want a function to do that (and notice how all the other solutions mentioning a function use an ugly subshell):
如果你想要一个函数来做到这一点(并注意所有其他提到函数的解决方案如何使用丑陋的子shell):
#!/bin/bash
# This wonderful function should be called thus:
# string_replace "replacement string" "$placeholder_string" variable_name
string_replace() {
printf -v "" ""
}
# 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.
评论。使用这种方法似乎printf
比 bash 的字符串替换略快。而且这里根本没有子shell!哇,这是西方最好的方法。
Funny.If you like funny stuff you could write the function string_replace
above as
有趣的。如果你喜欢有趣的东西,你可以把string_replace
上面的函数写成
string_replace() {
printf -v "$@"
}
# but then, use as:
string_replace destination_variable "$template" "$server"
回答by TheRuss
Yeah, either 'sed' as the others have said, or start with your template in 2 separate variables and construct on the fly. e.g.
是的,要么像其他人所说的那样“sed”,要么从 2 个单独的变量中的模板开始并即时构建。例如
templateprefix="my"
templatesuffix="appserver"
server=get_env
template=${templateprefix}${server}${templatesuffix}
回答by iarroyo
Based on @Spencer Rathbun
response, this can also be done this way:
根据@Spencer Rathbun
响应,这也可以通过以下方式完成:
function string_replace {
#DOC: "${string/match/replace}"
string=
echo "${string//}"
}
template='my__patternReplacing__appserver'
match='__patternReplacing__'
replace='live'
template=$(string_replace "$template" "$match" "$replace")
回答by Chris Moschini
I needed to do something like this, but I needed sed and the replace clause needed to include a variable. I ended up with this.
我需要做这样的事情,但我需要 sed 并且替换子句需要包含一个变量。我结束了这个。
Where the variable name is $puttyline
其中变量名是 $puttyline
sed "s/\(\[remote .origin.\]\)/\n$puttyline/"
So sed searches for [remote "origin"]
and remembers the match, and inserts a line right after, containing whatever's in the variable $puttyline
.
所以 sed 搜索[remote "origin"]
并记住匹配项,并在后面插入一行,包含变量中的任何内容$puttyline
。
This can get ugly however if $puttyline contains any special characters that sed would react to, like \ or $. You have to either escape them prior with another call to sed, or... do something smarter in bash that I'm too crappy with bash to know. For example, to double-escape all backslashes:
但是,如果 $puttyline 包含任何 sed 会做出反应的特殊字符,例如 \ 或 $,这可能会变得很丑陋。您必须在再次调用 sed 之前逃脱它们,或者...在 bash 中做一些更聪明的事情,我对 bash 太蹩脚了不知道。例如,要双重转义所有反斜杠:
sed 's/\/\\/g'
回答by Brad Parks
Here's a bash script that wraps this up
这是一个包含此内容的 bash 脚本
Example:
例子:
$ search_and_replace.sh "test me out" "test me" ez
ez out
search_and_replace.sh
search_and_replace.sh
#!/bin/bash
function show_help()
{
echo ""
echo "usage: SUBJECT SEARCH_FOR REPLACE_WITH"
echo ""
echo "e.g. "
echo ""
echo "test t a => aesa"
echo "'test me out' 'test me' ez => ez out"
echo ""
exit
}
if [ "" == "help" ]
then
show_help
exit
fi
if [ -z "" ]
then
show_help
exit
fi
SUBJECT=
SEARCH_FOR=
REPLACE_WITH=
echo "$SUBJECT" | sed -e "s/$SEARCH_FOR/$REPLACE_WITH/g"
回答by Rahul k
There are so many posts available online but the one which worked fine for me is as below.
网上有很多帖子,但对我来说效果很好的帖子如下。
There are 2 ways to achieve this, if you want to replace a string (my old string is with special character :) with another string in a file, then use this:
有两种方法可以实现这一点,如果你想用文件中的另一个字符串替换一个字符串(我的旧字符串带有特殊字符:),那么使用这个:
sed -i '/oldtext:/c\newtext: Rahul' ./printName.txt
Secondly, if you want to search for a string and then replace it with your variable, then do this:
其次,如果您想搜索一个字符串,然后将其替换为您的变量,请执行以下操作:
#here im concatinating two key + value(myvariable).
firstkey="oldtext: old"
key="newtext: "
value=$(cat ./variableStoredHere.txt)
key+=$value
result for below command will be oldtext: old
以下命令的结果将是 oldtext: old
echo $firstkey
result for below command will be will be newtext: Rahul
以下命令的结果将是 newtext:Rahul
echo $key
sed -i "s/$firstkey/$key/g" ./printName.txt