dotslash
dotslash

Reputation: 381

How to replace quotation marks in a JSON file with \" in bash?

For example, there is a string value read from a line of file.

{"ip":"91.239.165.20","timestamp":"2015-10-16T14:14:31-04:00","data":{"banner":"220 ********.****rn","ehlo":"502 Error: command "EHLO" not implementedrn","starttls":"502 Error: command "STARTTLS" not implementedrn"},"error":"Bad return code for STARTTLS","error_component":"starttls"}

As you can see there is a phrase "EHLO" was included in a string, it is like

"something "EHLO" the end"

But now I want to make this line looks like this,

"something \\"EHLO\\"   the end"

How to transform replace quotation marks in this line of JSON data?

In bash, regex or whatever...

It should be run in command line.

Many thanks!

Upvotes: 1

Views: 175

Answers (1)

Ed Morton
Ed Morton

Reputation: 203995

Using GNU awk for the 4th arg to split(), this will work with lines formatted as you've shown:

$ cat tst.awk
{
    n = split($0,f,/{"|"}|":{?"|"}?,"/,s)
    for (i=1; i<=n; i++) {
        gsub(/"/,"\\\"",f[i])
        printf "%s%s", f[i], (i<n ? s[i] : ORS)
    }
}

$ awk -f tst.awk file
{"ip":"91.239.165.20","timestamp":"2015-10-16T14:14:31-04:00","data":{"banner":"220 ********.****rn","ehlo":"502 Error: command \"EHLO\" not implementedrn","starttls":"502 Error: command \"STARTTLS\" not implementedrn"},"error":"Bad return code for STARTTLS","error_component":"starttls"}

If you have other formats that this doesn't work with then you should edit your question to make sure the sample input/output you provide is more truly representative of your real data.

Upvotes: 1

Related Questions