Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace double quotes by escaped double quote in awk?

Tags:

regex

awk

In awk how can I replace all double quotes by escaped double quotes?

The dog is "very" beautiful

would become

The dog is \"very\" beautiful

I've seen this answer (Using gsub to replace a double quote with two double quotes?) and I've tried to adapt it, but I'm not very good with awk (and sed is no option because I work both on Linux and OS X and they have different 'sed' installed)

like image 805
pedrorijo91 Avatar asked May 19 '15 21:05

pedrorijo91


People also ask

How do you escape double quotes in awk?

One use of an escape sequence is to include a double-quote character in a string constant. Because a plain double quote ends the string, you must use ' \" ' to represent an actual double-quote character as a part of the string. For example: $ awk 'BEGIN { print "He said \"hi!\

How do you escape double quotes in double quotes?

If you use single quotes to create a string, you can not use single quotes within that string without escaping them using a backslash ( \ ). The same theory applies to double quotes, and you have to use a backslash to escape any double quotes inside double quotes.

How do you escape a double quoted string?

String literalsDouble quote characters (") are escaped by a backslash (\)." Enclose the string in single-quotes ( ' ): 'Another string literal. Single quote characters (') require escaping by a backslash (\).

How do you escape a double quote in Unix?

' appearing in double quotes is escaped using a backslash. The backslash preceding the ' ! ' is not removed. The special parameters ' * ' and ' @ ' have special meaning when in double quotes (see Shell Parameter Expansion).


1 Answers

From the answer you linked:

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 output is:

The dog is \"very\" beautiful

like image 123
JosEduSol Avatar answered Sep 17 '22 10:09

JosEduSol