为什么unix读时不读最后一行? [英] Why does unix while read not read last line?
问题描述
我的脚本
export IFS=":"
cat hello | while read a b c d; do
echo $a,$b,$c,$d
done
我的文件hello
1:1:1:1
2:2:2:2
3:3:3:3
我的输出
1,1,1,1
2,2,2,2
如果我在hello
中的3:3:3:3
之后放置空白行,则输出将变为
If I put a blank line after 3:3:3:3
in hello
then the output becomes
1,1,1,1
2,2,2,2
3,3,3,3
任何人都知道如何解决此问题,因此我不需要在hello
的末尾插入空白行?
Anyone know how I can fix this problem so I don't need to put a blank line at the end of hello
?
推荐答案
发生了什么事,当输入未以换行符终止时,read
命令失败.由于文件末尾缺少换行符,因此read
失败,因此将跳过while
循环的最后一次迭代.
What's happening is, the read
command fails when the input is not terminated with a newline. Since the newline character is missing at the end of your file, the read
fails, so the last iteration of the while
loop is skipped.
如果您不想/不能确保输入文件的末尾有换行符,可以将cat
与echo
分组以给出外观输入由换行符终止,例如:
If you don't want to / cannot make sure that your input file has a newline at the end, you can group your cat
with an echo
to give the appearance of an input terminated by newline, for example like this:
{ cat hello; echo; } | while read a b c d; do
echo $a,$b,$c,$d
done
或类似这样:
(cat hello; echo) | while read a b c d; do
echo $a,$b,$c,$d
done
这篇关于为什么unix读时不读最后一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!