如果我使用单引号括起 awk 的操作语句,它会按预期工作:
$ dpkg -l | grep "linux\-[a-z]*\-" | awk {'print $2'}
linux-headers-3.13.0-27
linux-headers-3.13.0-27-generic
linux-headers-3.14.4-031404
linux-headers-3.14.4-031404-generic
linux-headers-generic
linux-image-3.13.0-27-generic
linux-image-3.14.4-031404-generic
linux-image-extra-3.13.0-27-generic
linux-image-generic
linux-libc-dev:i386
linux-sound-base
但是如果我使用双引号将它们括起来,它会打印整行而不是特定的列/字段:
$ dpkg -l | grep "linux\-[a-z]*\-" | awk {"print $2"}
ii linux-headers-3.13.0-27 3.13.0-27.50 all Header files related to Linux kernel version 3.13.0
ii linux-headers-3.13.0-27-generic 3.13.0-27.50 i386 Linux kernel headers for version 3.13.0 on 32 bit x86 SMP
ii linux-headers-3.14.4-031404 3.14.4-031404.201405130853 all Header files related to Linux kernel version 3.14.4
ii linux-headers-3.14.4-031404-generic 3.14.4-031404.201405130853 i386 Linux kernel headers for version 3.14.4 on 32 bit x86 SMP
ii linux-headers-generic 3.13.0.27.33 i386 Generic Linux kernel headers
ii linux-image-3.13.0-27-generic 3.13.0-27.50 i386 Linux kernel image for version 3.13.0 on 32 bit x86 SMP
ii linux-image-3.14.4-031404-generic 3.14.4-031404.201405130853 i386 Linux kernel image for version 3.14.4 on 32 bit x86 SMP
ii linux-image-extra-3.13.0-27-generic 3.13.0-27.50 i386 Linux kernel extra modules for version 3.13.0 on 32 bit x86 SMP
ii linux-image-generic 3.13.0.27.33 i386 Generic Linux kernel image
ii linux-libc-dev:i386 3.13.0-27.50 i386 Linux Kernel Headers for development
ii linux-sound-base 1.0.25+dfsg-0ubuntu4 all base package for ALSA and OSS sound systems
为什么会这样?为什么使用双引号括起 awk 的操作语句与使用单引号括起时产生的结果不同?我可以做些什么让使用双引号括起的结果与使用单引号括起的结果一样吗?
答案1
如果使用双引号,则在调用$2
之前由 shell 替换。通常为空运行awk
$2
awk {"print $2"}
和跑步一样
awk {"print "}
使用
awk {"print \$2"}
如果您想使用双引号。