搜索和多行shell变量替换shell变量 [英] Search and replace shell variable with multiline shell variable
问题描述
我知道有很多类似的问题,但我猜是因为搜索的格式/替换他们没有我的情况的工作变量。
I know there are lots of similar questions but, I guess because of the formatting of the search/replace variables they are not working for my situation.
我的工作将读取的文本文件(使用grep和awk的组合)来创建两个shell变量,$查找和替换$整体脚本。 $发现是一个包含字符的所有方式单行字符串。 $取而代之的是包含字符的所有方式多行字符串。
The overall script I am working on will read a text file (using combinations of grep and awk) to create two shell variables, $find and $replace. $find is a single line string containing all manner of characters. $replace is a multiline string containing all manner of characters.
例如:
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
现在我只需要替换为$找到$替换。我已经试过sed和perl的,但它失败。
Now I just need to substitute $find with $replace. I have tried sed and perl but it fails.
尝试(很多其他的东西之间)
Tried (among a lot of other stuff)
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
我的猜测是,问题是由字符串中的某个字符被引起跨preTED为特殊字符。
My guess is the problems are caused by some character in the string being interpreted as special characters.
任何帮助AP preciated!
Any help is appreciated!
推荐答案
这将会对任何参数值的查找或替换:
This will work for any values of find or replace:
$ cat file
foo
type result input1 another_input random_input<10> / name
bar
$ awk -v find="$find" -v replace="$replace" 's=index($0,find){$0=substr($0,1,s-1) replace substr($0,s+length(find))}1' file
foo
.TAG name
result input1 random_input / name1
random_input<10> input1 another_input / name2
.NTAG
bar
如果找到
始终是一整行,可以简化,例如这可能是你所需要的:
if find
is always one whole line it can be simplified, e.g. this might be all you need:
$ awk -v find="$find" -v replace="$replace" '$0==find{$0=replace}1' file
foo
.TAG name
result input1 random_input / name1
random_input<10> input1 another_input / name2
.NTAG
bar
这篇关于搜索和多行shell变量替换shell变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!