【问题标题】:Why is shell removing whitespaces when using substring? [duplicate]为什么在使用子字符串时 shell 会删除空格? [复制]
【发布时间】:2018-08-31 08:25:24
【问题描述】:

当打印开头有空格的子字符串时,会删除前导空格。

$ line="C , D,E,";
$ echo "Output-`echo ${line:3}`";
Output-D,E,

为什么要从输出中删除前导空格以及如何打印空格?

【问题讨论】:

    标签: bash shell split ksh


    【解决方案1】:

    子串操作

    ${line:3}
    

    将提取从位置 3 开始的所有字符,这确实是:[ D,E,](我添加 [] 只是为了便于阅读)。

    但是,在命令替换echo ${line:3} 中,shell 执行分词并删除前导空白字符,结果为D,E,

    将子字符串表达式放在双引号中以保留前导空格,如下所示:

    echo "Output-"`echo "${line:3}"` # => Output- D,E,
    

    为了更清楚地理解这一点,试试这个:

    line="C , D,E,"             # $() does command substitution like backquotes; it is a much better syntax
    string1=$(echo "${line:3}") # double quotes prevent word splitting
    string2=$(echo ${line:3})   # no quotes, shell does word splitting
    string3="$(echo ${line:3})" # since double quotes are outside but not inside $(), shell still does word splitting
    echo "string1=[$string1], string2=[$string2], string3=[$string3]" 
    

    给出输出:

    string1=[ D,E,], string2=[D,E,], string3=[D,E,]
    

    另见:

    【讨论】:

      【解决方案2】:

      Shell 不会在参数之间保留多个空格,因此两个空格合并为一个。

      echo "Output-`echo ${line:3}`";
      

      评估为:

      echo "Output-`echo  -D,E,`";
      

      还有:

      echo  -D,E,
      

      评估为:

      -D,E,
      

      换句话说,echo 为这两个调用接收相同的参数:

      echo  -D,E,
      echo -D,E,
      

      当参数作为字符串数组到达时,结束每个字符串已经被修剪(周围没有空格)。

      【讨论】:

      • 如果字符串被拆分为多个单词(随后作为单独的参数传递),这些空格只是“参数之间的”。正确引用扩展名将防止这种情况发生。
      猜你喜欢
      • 2021-12-01
      • 2013-06-06
      • 2017-05-16
      • 2017-03-19
      • 1970-01-01
      • 2012-11-19
      • 2014-05-18
      • 1970-01-01
      相关资源
      最近更新 更多