Replacing words with specified words using AWK

My code generates several json file all of which look similar to

{ "instance": "sample_instance_05", "steps": [ { "129": "North", "14": "North", "82": "North", "53": "North", "149": "North", "6": "North", "79": "North", "40": "North", "151": "North",

These files are all inside a single directory. My boss just told me that I should have generated the data with N for North, S for South, E for East and W for West.

Since these data files took quite some time to generate, I don't want to rerun the code again for such a simple text-replacement. AWK/SED/GREP etc. are clearly the took for the job (I have used a bit of AWK before, but I am quite rusty)

Is there a simpler Bash + AWK loop, which allows me to transform all the lines in the file as indicated?

1 Answer

sed method

I suggest using sed. The following should work to replace all instances of word_1 to word_2 in myfile.json.

$ sed -i 's/word_1/word_2/g' myfile.json

For example, to change "North" to "N":

$ sed -i 's/North/N/g' myfile.json

Note that the -i flag will invoke in-place editing and as such data will immediately be changed.

awk method

You can also use awk as such:

$ awk '{gsub(/word_1/,"word_2")}1' myfile.json > patchedfile.json

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like