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

sh/bash/dash/ksh/zsh等Shell脚本
回复
iamcook84
帖子: 41
注册时间: 2013-08-29 9:27

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

#1

帖子 iamcook84 » 2014-05-12 17:51

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>


为什么最后一行无法输出呢?
头像
YeLee
论坛版主
帖子: 26406
注册时间: 2008-08-13 8:48
系统: Fundu i64
来自: 东海硇州,一双管钥。
联系:

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

#2

帖子 YeLee » 2014-05-12 18:09

把光标移动到最后一行的末尾,按下回车键,谢谢。 :em01
◎当我站在道德的高度上俯视别人的时候,发现自己是多么渺小。
♥执着但不偏激,反对而不排斥,坚决捍卫矛盾体的存在方式。
★★★天气预报★★★
fcitx-yatable一个可以使用的码表输入法
[教程]几个实例攻克软件编译难关
Gentoo Development Guide
字体相关
头像
astolia
论坛版主
帖子: 6703
注册时间: 2008-09-18 13:11

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

#3

帖子 astolia » 2014-05-12 18:09

因为那个文本文件不是以空行结尾,即它不是一个符合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
回复