且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

搜索和多行shell变量替换shell变量

更新时间:2023-12-05 15:13:52

这将会对任何参数值的查找或替换:

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