Find and replace in awk

I have a file that I am trying to find a specific word, then replace text within that string.

file

TestA2015
TestB2016 

Example. Replace TestB2016 to TestB0000, so if TestB is found replace the original "2016" to "0000". Thank you :).

awk tried

awk '{ sub(/TestB$/, "0000", $6) }1' file

Your request (again!) is far from being complete and specific. Without trying to infer anything, this

awk '/TestB/ { sub(/2016/, "0000") }1' file
TestA2015
TestB0000

will exactly fulfill your requirement based on your sample.

1 Like

I am sorry for the lack of detail. The string TestB will always be the same. The digits after it vary as sometimes it will be 2016 others 2020, and others 2022. Thank you :).

If you know the field that TestB will always appear, then sub() can be replace by a simple assignment

e.g.

awk '$6 ~ /TestB/ {$6="TestB0000"}1' cmccabe.file 
1 Like

A work for sed.

Thank you :).