Reputation: 430
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
Upvotes: 1
Views: 516
Reputation: 785631
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
Upvotes: 2