Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 用sed替换多个字符串_Bash_Shell_Sed - Fatal编程技术网

Bash 用sed替换多个字符串

Bash 用sed替换多个字符串,bash,shell,sed,Bash,Shell,Sed,我正在使用sed替换包含以下内容的文本文件中的字符串: prop="distributed-${DEPLOY_ENV}.properties, database-${DEPLOY_ENV}.properties, compute-${DEPLOY_ENV}.properties" 在脚本中使用以下命令: #!/usr/bin/env bash env=dev sed \ -e "s/\${DEPLOY_ENV}/"${env}"/" \ 但是我得到以下输出;仅替换第一个出现的DEPLOY\u

我正在使用
sed
替换包含以下内容的文本文件中的字符串:

prop="distributed-${DEPLOY_ENV}.properties, database-${DEPLOY_ENV}.properties, compute-${DEPLOY_ENV}.properties"
在脚本中使用以下命令:

#!/usr/bin/env bash
env=dev
sed \
-e "s/\${DEPLOY_ENV}/"${env}"/" \
但是我得到以下输出;仅替换第一个出现的
DEPLOY\u ENV

prop="distributed-dev.properties, database-${DEPLOY_ENV}.properties, compute-${DEPLOY_ENV}.properties"
如何替换所有实例而不是第一个实例?

sed“s/\${DEPLOY\u ENV}/“${ENV}”/g”

为全局添加
/g

sed“s/\${DEPLOY\u ENV}/“${ENV}”/g”


为全局添加
/g

您只需要通过添加“g”使作用域成为全局的,这样您就可以影响所有匹配的出现

#!/usr/bin/env bash
set -x
env=dev
sed \
-e "s/\${DEPLOY_ENV}/"${env}"/g" \
然后按如下方式运行命令(其中text\u file\u with_envs.txt表示原始文件,text\u file\u with_envs.txt.new表示更新文件):


您只需要通过添加“g”使作用域成为全局的,以便影响匹配的所有出现

#!/usr/bin/env bash
set -x
env=dev
sed \
-e "s/\${DEPLOY_ENV}/"${env}"/g" \
然后按如下方式运行命令(其中text\u file\u with_envs.txt表示原始文件,text\u file\u with_envs.txt.new表示更新文件):

正确的语法是:

$ env=dev
$ sed 's/${DEPLOY_ENV}/'"$env"'/g' file
prop="distributed-dev.properties, database-dev.properties, compute-dev.properties"
正确的语法是:

$ env=dev
$ sed 's/${DEPLOY_ENV}/'"$env"'/g' file
prop="distributed-dev.properties, database-dev.properties, compute-dev.properties"

不,这是在错误的位置使用了错误的引号,因此将整个脚本暴露给shell进行变量扩展(这就是为什么您必须转义
$
),并删除$env周围的所有引号,这将使$env暴露给shell进行分词、生成文件名,等等。除非你有非常具体的理由不引用脚本和字符串(本例中没有),否则请始终将脚本和字符串用单引号括起来,并且除非你需要shell访问变量,否则必须引用变量-请参阅。不,这是在错误的位置使用了错误的引号,因此将整个脚本公开给shell进行变量扩展(这就是为什么您必须转义
$
)并删除$env周围的所有引号,这将使$env暴露在shell中,用于分词、文件名生成等。除非您有非常具体的理由不这样做,否则始终将脚本和字符串括在单引号中(本例中没有)你必须引用你的变量,除非你需要shell来访问它们-参见。