Search code examples
bashawkbackslashcommand-substitution

Escaping backslash in AWK in command substituion


I am trying to escape backslash in AWK. This is a sample of what I am trying to do.

Say, I have a variable

$echo $a
hi

The following works

$echo $a | awk '{printf("\\\"%s\"",$1)'}
\"hi"

But, when I am trying to save the output of the same command to a variable using command substitution, I get the following error:

$ q=`echo $a | awk '{printf("\\\"%s\"",$1)'}`
awk: {printf("\\"%s\"",$1)}
awk:               ^ backslash not last character on line

I am unable to understand why command substitution is breaking the AWK. Thanks a lot for your help.


Solution

  • Try this:

    q=$(echo $a | awk '{printf("\\\"%s\"",$1)}')
    

    Test:

    $ a=hi
    $ echo $a
    hi
    $ q=$(echo $a | awk '{printf("\\\"%s\"",$1)}')
    $ echo $q
    \"hi"
    

    Update:

    It will, it just gets a littler messier.

    q=`echo $a | awk '{printf("\\\\\"%s\"",$1)}'`
    

    Test:

    $ b=hello
    $ echo $b
    hello
    $ t=`echo $b | awk '{printf("\\\\\"%s\"",$1)}'`
    $ echo $t
    \"hello"
    

    Reference