Home > OS >  Escape double quotes in string inside awk pattern
Escape double quotes in string inside awk pattern

Time:11-11

In my bash script, at some point, I have some like:

<mycommand> | awk '
    ...
    $1 == "array" { test = 1 }
    END { if (test) run() }
    function run() {
        print "Messages:", _msg

        cmd="curl -s \""URL"\" -F \"param1="_param1"\" -F \"message="_msg"\" > /dev/null "
        system(cmd);

        fflush()
    }
'

so when run() executes, it prints something and then sends a system curl to somewhere!

My problem is that the _msg variable is a string having multiple " so the output could be something like:

"Messages:": "text1", "text2", "text3"

so when I pass it to curl I get sh: 1: Syntax error: Unterminated quoted string.

How can I correctly pass it to the cmd variable? I'd need to escape " right? How to do that?

Thanks

CodePudding user response:

Just add theese lines:

gsub(/\\/, "\\\\", _msg);
gsub(/"/, "\\\"", _msg);

just before cmd variable construction.

The first line add \ before each \.

The second line add \ before each ".

  • Related