本文介绍了如果没有在特定字符串之前将其替换为另一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用Shell脚本在多个文件中将"if"替换为"abc if".但是我不想更改是否在其他时间之前?
How to replace "if" to "abc if" in multiple file using shell scripting. But I don't want to change if when it preceded by else?
例如:
if (var3 == 4'h0)
a = bvec[0];
else
if (var3 == 4'h1)
a = bvec[1];
应转换为
abc if (var3 == 4'h0)
a = bvec[0];
else
if (var3 == 4'h1)
a = bvec[1];
请注意:1. else和if之间可以有不确定的空间或换行.2.文件中还有更多代码3.我希望更改仅在同一文件中进行.4.我想将文件名列表传递给脚本
Please note:1.there are can be indefinite space or a new line between else and if.2. There are more codes present in the file also3. I wanted the changes to occur in the same file only.4. I want to pass a list of filename to the script
我尝试过:
sed -r 's/else[[:blank:]]if/temp1/g;s/if/abc if/g;s/temp1/else if/g' file.v
推荐答案
用于多字符RS,gensub()和单词边界的GNU awk:
WIth GNU awk for multi-char RS, gensub(), and word boundaries:
$ awk -v RS='^$' -v ORS= '{
gsub(/@/,"@A")
gsub(/#/,"@B")
$0 = gensub(/\<else(\s+)if\>/,"#\\1#","g")
gsub(/\<if\>/,"abc &")
$0 = gensub(/#(\s+)#/,"else\\1if","g")
gsub(/@B/,"#")
gsub(/@A/,"@")
print
}' file
abc if (var3 == 4'h0)
a = bvec[0];
else
if (var3 == 4'h1)
a = bvec[1];
这篇关于如果没有在特定字符串之前将其替换为另一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!