[英]Bash sed muti word find and replace
I am getting the error "unterminated substitute pattern" on mac os when attempting to replace multiple words with a different set of multiple words separated by spaces. 尝试用空格分隔的一组不同的多个单词替换多个单词时,在Mac OS上出现错误“未终止的替换模式”。 I am doing this in a bash script. 我正在bash脚本中执行此操作。 Reading from csv to replace a set of strings in files. 从csv读取以替换文件中的一组字符串。
example 例
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
I want the output to be "another set of words" can't seem to find out how to allow the spaces in the expression. 我希望输出是“另一组单词”,似乎无法找出如何在表达式中保留空格。
Thanks 谢谢
You are defining the substitution to do in a variable so that you use later on: 您正在定义要在变量中进行的替换,以便稍后使用:
REGX="'s|$col2|$col3|g'"
sed -i -e REGX col3
Another example: 另一个例子:
$ cat a
hello this is a test
$ REGX="s/this/that/g"
$ sed $REGX a
hello that is a test
However, I would directly use the command as follows: 但是,我将直接使用以下命令:
while IFS=, read -r col1 col2 col3
do
sed -i.bak -e "s|$col2|$col3|g" $col1
done < $config_file
Notes: 笔记:
-r
in read
to avoid weird situations on corner cases. 在read
使用-r
可以避免在极端情况下出现怪异情况。 sed
so that the variables within the expression are evaluated. 在sed
使用双引号,以便对表达式中的变量进行求值。 Otherwise, it will look for literal $col2
and change with literal $col3
. 否则,它将查找文字$col2
并更改为文字$col3
。 -i.bak
to create backup files when using -i
. 使用-i
时,请使用-i.bak
创建备份文件。 Otherwise, if you try and fail... you will lose your original document. 否则,如果尝试失败...将会丢失原始文档。 sed -i "s#foo bar#another set of words#g"
# OR
sed -i "s#foo|bar#another string#g"
sed use |
sed使用|
as regex OR
, use another separator (the default /
suite well here also) 作为正则表达式OR
,请使用另一个分隔符(默认的/
suite也可以在这里使用)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.