Bash sed muti word查找和替换

时间:2014-09-29 13:05:53

标签: regex bash sed

当我尝试用空格分隔的多个单词的不同组替换多个单词时,我在mac os上收到错误“未终止的替换模式”。我在bash脚本中这样做。从csv读取以替换文件中的一组字符串。

例如

while IFS=, read col1 col2 col3

#$col1=FOO BAR
#$col2=another set of words
#$col3=file

do
   REGX="'s|$col2|$col3|g'"
   sed -i -e $REGX $col1
done < $config_file

我希望输出为“另一组单词”似乎无法找出如何允许表达式中的空格。

由于

2 个答案:

答案 0 :(得分:1)

您正在定义要在变量中执行的替换,以便稍后使用:

REGX="'s|$col2|$col3|g'"
sed -i -e REGX col3

另一个例子:

$ cat a
hello this is a test
$ REGX="s/this/that/g"
$ sed $REGX a
hello that is a test

但是,我会直接使用以下命令:

while IFS=, read -r col1 col2 col3
do
   sed -i.bak -e "s|$col2|$col3|g" $col1
done < $config_file

注意:

  • -r中使用read,以避免在角落情况下出现奇怪情况。
  • sed中使用双引号,以便计算表达式中的变量。否则,它会查找文字$col2并使用文字$col3进行更改。
  • 使用-i.bak时,使用-i创建备份文件。否则,如果您尝试失败......您将丢失原始文档。

答案 1 :(得分:0)

sed -i "s#foo bar#another set of words#g"
# OR
sed -i "s#foo|bar#another string#g"

使用|作为正则表达式OR,使用其他分隔符(此处也是默认的/套件)

相关问题