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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.