通过剪切命令

时间:2017-11-30 16:32:48

标签: linux string bash shell scripting

问题是:显示每行文字和字符。

这是我的代码:

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

如何解决这个问题?

3 个答案:

答案 0 :(得分:4)

您需要引用变量。当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

答案 1 :(得分:1)

简单的变化:

---纯粹的 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

答案 2 :(得分:0)

我也修好了

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