我正在编写一个shell脚本以将空白的数量读取到文件中。
我正在使用以下模板读一行
while read l
do
done <filename
,但它在阅读一条线时将多个空间转换为一个空间。
akash,您正在遇到问题,因为您未能引用echo
输出的 s-Splitting 的变量(以及其他任何命令)给人的印象是没有保留空格。要纠正问题,始终引用您的变量,例如
#!/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 < "$1"
示例输入文件
$ 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)
示例使用/输出
$ 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 "%sn%dn" "$l" "${#l}"
done < "$1"