-1

我有一个脚本

index=0
while read line 
do  
  echo "read line is $line" 
  line=`echo ${line}|awk '{print $1}'`  

  index=$((index+1)) 

  if((index%2==0));then 
    echo "before continue line is $line"  
    continue 
  fi   

  echo "index is $index and now modify html page with $line" 
  ...
  ...
  done< infile

infile 的内容是:

1OrMcP2CdV4 180 

1Wp33RG2XaA 180 

21zUUJ04ovI 180 

2pIqUhaDMLg 180 

2WRU4NUJSVc 180 
...
...

在infile中,有交替的空行,是我自己故意添加的,我为什么这样做,你可以参考http://goo.gl/K7g0m,这是“while read”循环的另一种奇怪行为。基本上,“读取”无法正确读取偶数行,因此我将偶数行设为空行。

我运行脚本,输出为:

read line is 1OrMcP2CdV4 180
index is 1 and now modify html page with 1OrMcP2CdV4


read line is 1Wp33RG2XaA 180
before continue line is 1Wp33RG2XaA


read line is 
index is 3 and now modify html page with 


read line is 21zUUJ04ovI 180
before continue line is 21zUUJ04ovI

read line is 
index is 5 and now modify html page with 

所以基本上,“while read loop”似乎按顺序读取行:1 3 2 5 4

然后我修改了空行,比如

1OrMcP2CdV4 180 
Axxx
1Wp33RG2XaA 180 
Axxx
21zUUJ04ovI 180 
Axxx 
2pIqUhaDMLg 180 
Axxx  
2WRU4NUJSVc 180 
...
..

输出很有趣:

read line is 1OrMcP2CdV4 180
index is 1 and now modify html page with 1OrMcP2CdV4

read line is xxx
before continue line is xxx


read line is 1Wp33RG2XaA 180
index is 3 and now modify html page with 1Wp33RG2XaA

read line is xxx
before continue line is xxx

read line is 21zUUJ04ovI
index is 5 and now modify html page with 21zUUJ04ovI 


read line is 21zUUJ04ovI 180
before continue line is 21zUUJ04ovI

好的,它现在按顺序读取,但是偶数行“Axxx”被读取为“xxx”,前20行似乎是按顺序排列的,但有时,顺序又乱了!有趣又奇怪,不是吗?

这种行为不端有什么问题?对于脚本,有几个后台命令,比如

firefox &
tcpdump &

也喜欢

sleep 5

详情可以参考上面的链接,这样会不会有子进程同步的问题?但我不这么认为。

这个问题真的很奇怪,我真的不知道如何处理它!

4

1 回答 1

0

所以你想得到每第二行的第一个字段?然后我建议类似:

while read id rest 
do
     # here code to process id
     #  .....
     read again # skip every other line
done

顺便说一句:index你的代码中的初始值是多少?

于 2012-11-02T22:52:39.397 回答