Thursday, February 8, 2024

[SOLVED] Find and replace for JSON with sed or awk

Issue

So I need to be able to inject a value into JSON using sed or awk (preferably on one line) and I cannot install any external libraries to help me.

An example of the json is something like {"version":"0.5363"}

I'd need to be able to inject a new value for version.

Any help would be greatly appreciated.


Solution

You could try the below sed command,

$ echo '{"version":"0.5363"}' | sed 's/\({"version":"\)[^"]*\("}\)/\1newvalue\2/g'
{"version":"newvalue"}

In the above sed command, replace the newvalue with value you want. Add inline edit option -i to save the changes made.

sed -i 's/regex/replacement/g' file


Answered By - Avinash Raj
Answer Checked By - Mary Flores (WPSolving Volunteer)