简体   繁体   English

用变量替换包含美元符号的 bash 脚本中的字符串

[英]Replace string in bash script that contains dollar sign with a variable

I have a bash script that reads a file that contains strings and I want to do some variable substitution before executing the commands.我有一个 bash 脚本,它读取包含字符串的文件,我想在执行命令之前进行一些变量替换。 It's pretty much what bash does itself.这几乎就是 bash 本身所做的。 The user will provide an array of substitution arguments to the script.用户将向脚本提供一个替换数组 arguments。 This seems pretty simple but I can't get the $ to be substituted in the string read from the file.这看起来很简单,但我无法在从文件中读取的字符串中替换 $。 Assume the STR is being read from a file and the ARGS are input to the script:假设正在从文件中读取 STR,并且将 ARGS 输入到脚本中:

#!/bin/bash
ARGS=(what string)
STR='This is ${1} my input ${2} string looks like. ${1}?'

v=1
for s in "${ARGS[@]}"
do
   #STR=`echo $STR | sed "s/'$'{$v}/$s/g"` #using this replaces nothing in STR
   STR=`echo $STR | sed "s/{$v}/$s/g"   #using this replaces the {number} correctly but leaves the $
   v=$((v+1))
done
echo $STR
# eval $STR

Running the above, gives: This is $what my input $string string looks like.运行上面的代码,给出: 这是我输入的 $string 字符串的样子。 $what? $什么? but I want the $ to not be there in the final STR.但我希望 $ 在最终的 STR 中不存在。

#!/bin/bash
ARGS=(what string)
STR='This is ${1} my input ${2} string looks like. ${1}?'

v=1
for s in "${ARGS[@]}"
do
   STR=`echo $STR | sed "s/\\${$v}/$s/g"`
   v=$((v+1))
done
echo $STR

This gets me this output, if I understood you correctly it is what you wanted.这给了我这个 output,如果我理解正确的话,这就是你想要的。

This is what my input string string looks like. what?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM