How to replace the second instance of a string wit

2019-08-10 11:52发布

I am trying to replace the second instance of the string FooBarr in a file with the value in the variable $myVar. AWK doesn't seem to parse the variable. Does anyone know what I'm doing wrong here please or have a better way forward please?

awk '/FooBarr /{c++;if(c==2){sub("FooBarr ",$myVar);c=0}}1' myFile

1条回答
孤傲高冷的网名
2楼-- · 2019-08-10 12:14

You need to use -v var=value syntax to pass the value to awk and use this logic little differently:

awk -v myVar="$myVar" '/FooBarr /{c++} c==2{sub("FooBarr ", myVar); c=0} 1' myFile

Or better to pass-in search term from command line as well:

awk -v s='FooBarr ' -v myVar="$myVar" '$0~s{c++} c==2{sub(s, myVar); c=0} 1' myFile
查看更多
登录 后发表回答