在 bash 中使用 While 循环读取一行时,它会将多个 space 压缩为一个
When reading a line using While loop in bash, it's squezzing multiple space into one
我正在编写一个 shell 脚本来将空白 space 的数量读入文件。
我正在使用以下模板逐行阅读
while read l
do
done <filename
但它在阅读一行时将多个 space 转换为一个 space。
Akash,你 运行 遇到了问题,因为你没有引用你的变量,这导致 word-splitting 来自 echo
的输出(以及任何其他命令)给人的印象是没有保留空格。要更正此问题,始终引用您的变量,例如
#!/bin/bash
while IFS= read -r l
do
echo "$l"
echo "$l" > tempf
wc -L tempf | cat > length
len=$(cut -d " " -f 1 length)
echo "$len"
done < ""
示例输入文件
$ cat fn
who -all
system boot 2019-02-13 10:27
run-level 5 2019-02-13 10:27
LOGIN tty1 2019-02-13 10:27 1389 id=tty1
david ? :0 2019-02-13 10:27 ? 3118
david - console 2019-02-13 10:27 old 3118 (:0)
示例Use/Output
$ bash readwspaces.sh fn
who -all
8
system boot 2019-02-13 10:27
40
run-level 5 2019-02-13 10:27
40
LOGIN tty1 2019-02-13 10:27 1389 id=tty1
66
david ? :0 2019-02-13 10:27 ? 3118
58
david - console 2019-02-13 10:27 old 3118 (:0)
63
此外,对于它的价值,您可以将脚本缩短为:
#!/bin/bash
while IFS= read -r l
do
printf "%s\n%d\n" "$l" "${#l}"
done < ""
我正在编写一个 shell 脚本来将空白 space 的数量读入文件。
我正在使用以下模板逐行阅读
while read l
do
done <filename
但它在阅读一行时将多个 space 转换为一个 space。
Akash,你 运行 遇到了问题,因为你没有引用你的变量,这导致 word-splitting 来自 echo
的输出(以及任何其他命令)给人的印象是没有保留空格。要更正此问题,始终引用您的变量,例如
#!/bin/bash
while IFS= read -r l
do
echo "$l"
echo "$l" > tempf
wc -L tempf | cat > length
len=$(cut -d " " -f 1 length)
echo "$len"
done < ""
示例输入文件
$ cat fn
who -all
system boot 2019-02-13 10:27
run-level 5 2019-02-13 10:27
LOGIN tty1 2019-02-13 10:27 1389 id=tty1
david ? :0 2019-02-13 10:27 ? 3118
david - console 2019-02-13 10:27 old 3118 (:0)
示例Use/Output
$ bash readwspaces.sh fn
who -all
8
system boot 2019-02-13 10:27
40
run-level 5 2019-02-13 10:27
40
LOGIN tty1 2019-02-13 10:27 1389 id=tty1
66
david ? :0 2019-02-13 10:27 ? 3118
58
david - console 2019-02-13 10:27 old 3118 (:0)
63
此外,对于它的价值,您可以将脚本缩短为:
#!/bin/bash
while IFS= read -r l
do
printf "%s\n%d\n" "$l" "${#l}"
done < ""