【问题标题】:Ignorance of spaces by cut command通过 cut 命令忽略空格
【发布时间】:2018-05-14 15:54:59
【问题描述】:

问题是:显示每行文本中的 and 字符。

这是我的代码:

while read line
do
    a=`echo $line | cut -c 2`
    b=`echo $line | cut -c 7`

    echo -n $a
    echo $b
done

问题是当第一个字符是空格时,它不打印空格。例如,

Input:
A big elephant

Expected output:
 e

My output:
e

如何解决这个问题?

【问题讨论】:

    标签: linux string bash shell scripting


    【解决方案1】:

    您需要引用变量。当 bash 扩展 $a 时,echo 不会打印空格,因为它不被视为参数。

    一个命令可以有很多尾随空格,但是由于 bash 默认使用空格来分隔命令和参数,任何额外的空格都将被忽略,除非是参数的明确部分(使用引号或转义)。

    例如:

    => echo a       # Argument without spaces works (at least in this case)
    a
    => echo  a      # Two spaces between, unquoted spaces are ignored
    a
    => echo " a"    # Quotes make the space part of the argument
     a
    => echo      a  # Arguments can have many spaces between them
    a
    => echo         # No quotes or spaces, echo sees no arguments, doesn't print anything
    
    => echo " "     # Space is printed (changed to an underscore, wouldn't actually be visible)
    _
    =>
    

    这也是为什么必须在文件名中转义空格的原因,除非它们被引用:

    => touch file 1      # Makes two files: "file" and "1"
    => touch "file 1"    # Makes one file: "file 1"
    => touch file\ 1     # Makes one file: "file 1"
    

    您的最终代码是:

    while read line
    do
        a=`echo $line | cut -c 2`
        b=`echo $line | cut -c 7`
    
        echo -n "$a"
        echo "$b"
    done
    

    【讨论】:

      【解决方案2】:

      简单的变化:

      --- 纯bash(基于切片):

      s="A big elephant"
      echo "${s:1:1}${s:8:1}"
       e
      

      --- bash + cut:

      s="A big elephant"
      cut -c 2,7 <<<"$s"
       e
      

      【讨论】:

        【解决方案3】:

        我也修好了

        while read line
        do
           a=`echo $line | cut -c 2`
           b=`echo $line | cut -c 7`    
        echo "$a$b"
        done
        

        【讨论】:

          猜你喜欢
          • 2010-10-23
          • 1970-01-01
          • 2021-09-09
          • 1970-01-01
          • 2016-10-11
          • 1970-01-01
          • 1970-01-01
          • 2012-04-22
          • 1970-01-01
          相关资源
          最近更新 更多