Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 342
Bill Avatar asked May 28 '13 21:05

Bill


People also ask

How do you escape a backslash in awk?

Leave the backslash alone. Some other awk implementations do this. In such implementations, typing "a\qc" is the same as typing "a\\qc" .

How do I print awk?

To print a blank line, use print "" , where "" is the empty string. To print a fixed piece of text, use a string constant, such as "Don't Panic" , as one item. If you forget to use the double-quote characters, your text is taken as an awk expression, and you will probably get an error.


2 Answers

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

like image 163
jaypal singh Avatar answered Sep 19 '22 22:09

jaypal singh


Quoting inside backquoted commands is somewhat complicated, mainy because the same token is used to start and to end a backquoted command. As a consequence, to nest backquoted commands, the backquotes of the inner one have to be escaped using backslashes. Furthermore, backslashes can be used to quote other backslashes and dollar signs (the latter are in fact redundant). If the backquoted command is contained within double quotes, a backslash can also be used to quote a double quote. All these backslashes are removed when the shell reads the backquoted command. All other backslashes are left intact.

The new $(...) avoids these troubles.

like image 31
Uwe Avatar answered Sep 19 '22 22:09

Uwe