日期:2014-05-16  浏览次数:20675 次

关于一个shell脚本的不解之处
之前在python区发过这帖,需求目的是统计出连续0值出现的次数,按python来做就没什么问题,但是我转成shell实现,却遇到了一个不解的地方.

文本内容如下:
===================
0
0
590
0
0
1045
2251
1469
0
0
0
0
4396
0
0
4799
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
============
目的是统计出连续0值出现的次数.理论应该输出这样的结果:
2
2
4
2
16
==============
我写的shell如下:
#!/bin/bash
#name:counter.sh
#usage: count for 0

#set variable
filename="counter.txt"

#read file
counter=0
cat $filename | while read LINE
do
        LineText=$LINE
        if [ $LineText -eq 0 ]
                then
                counter=$(($counter+1))
        elif [ $counter -gt 0 ]
                then
                echo $counter
                counter=0
        fi

done

#test the last counter if>0 print
if [ $counter -gt 0 ] 
then
echo $counter
fi

===
最后在done之外echo了counter 的值得,发现竟然是0,求教
------解决方案--------------------
试试改成这样:
#!/bin/bash
#name:counter.sh
#usage: count for 0

#set variable
filename="counter.txt"

#read file
counter=0
while read LINE
do
        LineText=$LINE
        if [ $LineText -eq 0 ]
                then
                counter=$(($counter+1))
        elif [ $counter -gt 0 ]
                then
                echo $counter
                counter=0
        fi

done < $filename

#test the last counter if>0 print
if [ $counter -gt 0 ]
then
echo $counter
fi

------解决方案--------------------
引用:
大神,确实是可以了,可是原来为何呢~~为什么我先cat file 
------解决方案--------------------
 read line
从done里面定向 done < $filename有什么区别呢

cat 
------解决方案--------------------
 while 这种方式会启动一个 sub shell
------解决方案--------------------
引用