分页: 1 / 1

为什么最后一行无法输出呢?

发表于 : 2014-05-12 17:51
iamcook84
suse@linux-qmfx:~/program> cat -n sedrm.txt
1 a1
2 b2
3 c3
4 d4suse@linux-qmfx:~/program> cat real.sh
#!/bin/bash
loop=0
while read LINE
do
loop=`expr $loop + 1`
echo "at line$loop :$LINE"
done < sedrm.txt
echo "++++++++++++the end.total :$loop lines"

suse@linux-qmfx:~/program> sh real.sh
at line1 :a1
at line2 :b2
at line3 :c3
++++++++++++the end.total :3 lines
suse@linux-qmfx:~/program>


为什么最后一行无法输出呢?

Re: 为什么最后一行无法输出呢?

发表于 : 2014-05-12 18:09
YeLee
把光标移动到最后一行的末尾,按下回车键,谢谢。 :em01

Re: 为什么最后一行无法输出呢?

发表于 : 2014-05-12 18:09
astolia
因为那个文本文件不是以空行结尾,即它不是一个符合POSIX标准的文本文件。

read的文档中有提到它做了如下假定
Although the standard input is required to be a text file, and therefore will always end with a <newline> (unless it is an empty file),
所以如果文本文件不是以空行结尾,read返回值是非0值

如果你一定要处理这种文件,需要稍微改一下while的条件

代码: 全选

#!/bin/bash
loop=0
while read LINE || [ -n "$LINE" ]
do
loop=`expr $loop + 1`
echo "at line$loop :$LINE"
done < sedrm.txt
echo "++++++++++++the end.total :$loop lines"
更多详细信息你可以看这篇:http://stackoverflow.com/questions/1291 ... -last-line