Vij*_*j S 0 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
Run Code Online (Sandbox Code Playgroud)
问题是当第一个字符是空格时,它不会打印空格。例如,
Input:
A big elephant
Expected output:
e
My output:
e
Run Code Online (Sandbox Code Playgroud)
如何解决这个问题?
您需要引用变量。当 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)
_
=>
Run Code Online (Sandbox Code Playgroud)
这也是为什么必须在文件名中转义空格的原因,除非它们被引用:
=> 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"
Run Code Online (Sandbox Code Playgroud)
您的最终代码将是:
while read line
do
a=`echo $line | cut -c 2`
b=`echo $line | cut -c 7`
echo -n "$a"
echo "$b"
done
Run Code Online (Sandbox Code Playgroud)