Thursday, March 29, 2018

bash - Difference between single and double quotes in awk



I have this awk statement:



glb_library="my_library"
awk "

/^Direct Dependers of/ { next }
/^---/ { next }
/^$glb_library:/ { ver=\$0; next }
{ gsub(/[[:space:]]/, '', \$0); print ver':'\$0 }
" file


Basically, I have enclosed the awk code in double quotes so that the shell variable glb_library is expanded. I have made sure to escape the $ character to prevent the shell from expanding $0. Followed the guidance from here.



awk gives me this error:




awk: syntax error at source line 5
context is
{ gsub(/[[:space:]]/, >>> ' <<<


I want to understand:




  • Is it legal to use single quotes inside awk? Why is '' not a null string like "" is?


  • Does awk treat single and double quotes differently?



My code worked after I escaped the single quotes with backslashes and used \"\" to represent the null string instead of ''.


Answer



Based on the comments above by awk experts and some research, I am posting this answer:




  • awk strings are enclosed in double quotes, not single quotes; more precisely: single quotes are not string delimiters in awk, unlike shell

  • awk attaches no special meaning to single quotes and they need to be enclosed in double quotes if used in string literals


  • it is best to use single quotes to wrap awk statements on command line, unlike OP's code that's using double quotes (Ed pointed this out clearly)



Further clarification:




  • "" is the null string in awk, not ''

  • to use single quotes in an awk string literal, enclose them in double quotes, as in "Ed's answers are great!"

  • other techniques followed while handling single quotes in awk are:




    a) use a variable, as in awk -v q="'" '{ print q }' ...



    b) use octal or hex notation, as in awk '{ print "\047"$0"\047" }' ...







Relevant documentation here.


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...