How do I replace double quotes with an escaped double quote in awk?

In awk, how can I replace all double quotes with escaped double quotes?

The dog is "very" beautiful

      

will become

The dog is \"very\" beautiful

      

I saw this answer ( Using gsub to replace a double quote with two double quotes? ) And I tried to adapt it, but I am not very good with awk (and sed is not an option because I work on both Linux and OS X. and they have different "sed")

+3


source to share


2 answers


you can use with GNU awk:

echo 'The dog is "very" beautiful' | gawk '{ gsub(/"/,"\\\"") } 1'

      

You get



The dog is \"very\" beautiful

      

Explanation:

for special characters \

and "

, you must escape \\

and\"

+3


source


From the response received:

With gsub :

echo 'The dog is "very" beautiful' | gawk '{ gsub(/"/,"\\\"") } 1'

      

Alternative, with sed :



echo 'The dog is "very" beautiful' | sed 's/"/\\"/g'

      

In both cases, the output is:

The dog is very beautiful

+6


source







All Articles