gpt4 book ai didi

linux - cut 命令忽略空格

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:50:48 28 4
gpt4 key购买 nike

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

这是我的代码:

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

如何解决这个问题?

最佳答案

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

关于linux - cut 命令忽略空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47578214/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com