echo '1 2'|awk "{print $2}"的输出为什么是 1 2

2020-03-22 09:15:20 +08:00
 lasuar

awk 的语句改为双引号就变成了整行输出,双引号起了什么作用?请教==

5912 次点击
所在节点   Bash
12 条回复
ynyounuo
2020-03-22 09:22:45 +08:00
ynyounuo
2020-03-22 09:26:38 +08:00
ynyounuo
2020-03-22 09:27:08 +08:00
> Double quotes protect most things between the opening and closing quotes. The shell does at least variable and command substitution on the quoted text. Different shells may do additional kinds of processing on double-quoted text.
> Because certain characters within double-quoted text are processed by the shell, they must be escaped within the text. Of note are the characters ‘$’, ‘`’, ‘\’, and ‘"’, all of which must be preceded by a backslash within double-quoted text if they are to be passed on literally to the program.
widewing
2020-03-22 09:34:48 +08:00
shell $2=空字符串
lasuar
2020-03-22 09:35:48 +08:00
@ynyounuo 按文档的意思双引号就是保护了`$`,这里就变成了纯文本的 print $2,那么为什么会输出 1 2 呢?
sakuramanstein
2020-03-22 09:38:05 +08:00
看了一下楼上的答案,是不是这个意思 双引号内的字符串先由 shell 解析 于是$2 被解析为空(没有这个变量),等价于 awk "{print}",所以输出 1 2 。
lasuar
2020-03-22 09:39:02 +08:00
@widewing 行,大概明白了,我试了一下 awk 中没办法打印出文本的$,这个符号一定会被处理,只是处理方式不同
tlday
2020-03-22 09:40:38 +08:00
echo '1 2'|awk '{print $2}'
lasuar
2020-03-22 09:42:38 +08:00
@sakuramanstein 应该是这样的。但是在 awk 中好像没办法打印出文本的美元符了,通过 echo '$1'是可以的,awk 对单双引号的解释和 echo 对其的处理方式完全是相反的。
sakuramanstein
2020-03-22 09:49:42 +08:00
@lasuar 可以啊 awk '{print "$"}'
lasuar
2020-03-22 09:51:54 +08:00
@sakuramanstein 好的,3q==
labulaka521
2020-03-22 11:21:35 +08:00
awk 请使用单引号

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/655014

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX