Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
731 views
in Technique[技术] by (71.8m points)

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 ''.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Never enclose any script in double quotes or you're sentencing yourself to backslash-hell. This is the syntax for what you're trying to do:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...