【发布时间】:2015-03-10 20:34:02
【问题描述】:
我知道有很多类似的问题,但我猜是因为搜索/替换变量的格式,它们不适用于我的情况。
我正在编写的整个脚本将读取一个文本文件(使用 grep 和 awk 的组合)来创建两个 shell 变量,$find 和 $replace。 $find 是包含各种字符的单行字符串。 $replace 是一个包含各种字符的多行字符串。
示例:
echo "$find"
返回
type result input1 another_input random_input<10> / name
和
echo "$replace"
返回
.TAG name
result input1 random_input / name1
random_input<10> input1 another_input / name2
.NTAG
现在我只需要用 $replace 替换 $find。我试过 sed 和 perl 但都失败了。
尝试过(在很多其他的东西中)
perl -e -i.bak "s/$find/$replace/g" text.file
perl -e -i.bak 's,"'$find'","'$replace'",g' text.file
perl -e -i.bak "s|$find|$replace|g" text.file
和
sed -i "s/$find/$replace/g" text.file
我的猜测是问题是由字符串中的某些字符被解释为特殊字符引起的。
感谢任何帮助!
【问题讨论】:
-
不完全是,问题是当您要操作的是字符串时,您正在使用正则表达式构造。你不能用 sed 做到这一点,因为它只能在正则表达式上运行,我希望 perl 确实有一些构造来处理字符串,但那些不是你正在使用的构造。