V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
freemoon
V2EX  ›  Bash

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

  •  
  •   freemoon · Mar 22, 2020 · 6607 views
    This topic created in 2231 days ago, the information mentioned may be changed or developed.

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

    12 replies    2020-03-22 11:21:35 +08:00
    ynyounuo
        1
    ynyounuo  
       Mar 22, 2020   ❤️ 1
    ynyounuo
        3
    ynyounuo  
       Mar 22, 2020
    > 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  
       Mar 22, 2020 via Android
    shell $2=空字符串
    freemoon
        5
    freemoon  
    OP
       Mar 22, 2020
    @ynyounuo 按文档的意思双引号就是保护了`$`,这里就变成了纯文本的 print $2,那么为什么会输出 1 2 呢?
    sakuramanstein
        6
    sakuramanstein  
       Mar 22, 2020 via Android
    看了一下楼上的答案,是不是这个意思 双引号内的字符串先由 shell 解析 于是$2 被解析为空(没有这个变量),等价于 awk "{print}",所以输出 1 2 。
    freemoon
        7
    freemoon  
    OP
       Mar 22, 2020
    @widewing 行,大概明白了,我试了一下 awk 中没办法打印出文本的$,这个符号一定会被处理,只是处理方式不同
    tlday
        8
    tlday  
       Mar 22, 2020
    echo '1 2'|awk '{print $2}'
    freemoon
        9
    freemoon  
    OP
       Mar 22, 2020
    @sakuramanstein 应该是这样的。但是在 awk 中好像没办法打印出文本的美元符了,通过 echo '$1'是可以的,awk 对单双引号的解释和 echo 对其的处理方式完全是相反的。
    sakuramanstein
        10
    sakuramanstein  
       Mar 22, 2020 via Android
    @lasuar 可以啊 awk '{print "$"}'
    freemoon
        11
    freemoon  
    OP
       Mar 22, 2020
    @sakuramanstein 好的,3q==
    labulaka521
        12
    labulaka521  
       Mar 22, 2020 via Android
    awk 请使用单引号
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2460 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 46ms · UTC 06:00 · PVG 14:00 · LAX 23:00 · JFK 02:00
    ♥ Do have faith in what you're doing.