在 for 循环中使用带有变量的 sed 的 Bash 脚本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7033860/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:52:21  来源:igfitidea点击:

Bash script using sed with variables in a for loop?

bashvariablesscriptingsed

提问by LF4

I'm trying to write a bash script that takes a few variables and then does a find/replace with a given file search using grep to get the list of files that have the string. I think the issue I'm having is having the variables be seen in sed I'm not sure what else it might be.

我正在尝试编写一个 bash 脚本,它接受一些变量,然后使用 grep 使用给定的文件搜索进行查找/替换,以获取具有该字符串的文件列表。我认为我遇到的问题是在 sed 中看到变量我不确定它可能是什么。

if [ "$searchFiles" != "" -a "$oldString" != "" -a "$newString" != "" ]; then
   echo -en "Searching for '$searchFiles' and replacing '$oldString' with '$newString'.\n"
   for i in `grep $oldString $searchFiles |cut -d: -f1|uniq`; do
      sed -i 's/${oldString}/${newString}/g' $i;
   done
   echo -en "Done.\n"
else
   usage
fi

回答by Karoly Horvath

use double quotes so the shell can substitute variables.

使用双引号,以便 shell 可以替换变量。

for i in `grep -l $oldString $searchFiles`; do
  sed -i "s/${oldString}/${newString}/g" $i;
done

if your search or replace string contains special characters you need to escape them: Escape a string for a sed replace pattern

如果您的搜索或替换字符串包含特殊字符,您需要对它们进行转义:Escape a string for a sed replace pattern

回答by Conspicuous Compiler

Use double quotes so the environmental variables are expanded by the shell before it calls sed:

使用双引号,以便 shell 在调用 sed 之前扩展环境变量:

  sed -i "s/${oldString}/${newString}/g" $i;

Be wary: If either oldStringor newStringcontain slashes or other regexp special characters, they will be interpreted as their special meaning, not as literal strings.

小心:如果oldStringnewString包含斜杠或其他正则表达式特殊字符,它们将被解释为它们的特殊含义,而不是文字字符串。