V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
lasuar
V2EX  ›  Bash

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

  •  
  •   lasuar · 2020-03-22 09:15:20 +08:00 · 5905 次点击
    这是一个创建于 1495 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    12 条回复    2020-03-22 11:21:35 +08:00
    ynyounuo
        1
    ynyounuo  
       2020-03-22 09:22:45 +08:00   ❤️ 1
    ynyounuo
        2
    ynyounuo  
       2020-03-22 09:26:38 +08:00
    ynyounuo
        3
    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
        4
    widewing  
       2020-03-22 09:34:48 +08:00 via Android
    shell $2=空字符串
    lasuar
        5
    lasuar  
    OP
       2020-03-22 09:35:48 +08:00
    @ynyounuo 按文档的意思双引号就是保护了`$`,这里就变成了纯文本的 print $2,那么为什么会输出 1 2 呢?
    sakuramanstein
        6
    sakuramanstein  
       2020-03-22 09:38:05 +08:00 via Android
    看了一下楼上的答案,是不是这个意思 双引号内的字符串先由 shell 解析 于是$2 被解析为空(没有这个变量),等价于 awk "{print}",所以输出 1 2 。
    lasuar
        7
    lasuar  
    OP
       2020-03-22 09:39:02 +08:00
    @widewing 行,大概明白了,我试了一下 awk 中没办法打印出文本的$,这个符号一定会被处理,只是处理方式不同
    tlday
        8
    tlday  
       2020-03-22 09:40:38 +08:00
    echo '1 2'|awk '{print $2}'
    lasuar
        9
    lasuar  
    OP
       2020-03-22 09:42:38 +08:00
    @sakuramanstein 应该是这样的。但是在 awk 中好像没办法打印出文本的美元符了,通过 echo '$1'是可以的,awk 对单双引号的解释和 echo 对其的处理方式完全是相反的。
    sakuramanstein
        10
    sakuramanstein  
       2020-03-22 09:49:42 +08:00 via Android
    @lasuar 可以啊 awk '{print "$"}'
    lasuar
        11
    lasuar  
    OP
       2020-03-22 09:51:54 +08:00
    @sakuramanstein 好的,3q==
    labulaka521
        12
    labulaka521  
       2020-03-22 11:21:35 +08:00 via Android
    awk 请使用单引号
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   6003 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 02:11 · PVG 10:11 · LAX 19:11 · JFK 22:11
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.