【发布时间】:2018-08-31 08:25:24
【问题描述】:
当打印开头有空格的子字符串时,会删除前导空格。
$ line="C , D,E,";
$ echo "Output-`echo ${line:3}`";
Output-D,E,
为什么要从输出中删除前导空格以及如何打印空格?
【问题讨论】:
当打印开头有空格的子字符串时,会删除前导空格。
$ line="C , D,E,";
$ echo "Output-`echo ${line:3}`";
Output-D,E,
为什么要从输出中删除前导空格以及如何打印空格?
【问题讨论】:
子串操作
${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,]
另见:
【讨论】:
Shell 不会在参数之间保留多个空格,因此两个空格合并为一个。
echo "Output-`echo ${line:3}`";
评估为:
echo "Output-`echo -D,E,`";
还有:
echo -D,E,
评估为:
-D,E,
换句话说,echo 为这两个调用接收相同的参数:
echo -D,E,
echo -D,E,
当参数作为字符串数组到达时,结束每个字符串已经被修剪(周围没有空格)。
【讨论】: