freemoon
V2EX  ›  Bash

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

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

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

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