首页 > 系统服务 > 详细

Shell逐行读取文件的3种方法

时间:2017-11-20 17:06:50      阅读:182      评论:0      收藏:0      [点我收藏+]

方法1:while循环中执行效率最高,最常用的方法。

while read line
do
echo $line
done  < filename

注释:这种方式在结束的时候需要执行文件,就好像是执行完的时候再把文件读进去一样。

 

方法2 : 管道法: cat $FILENAME | while read LINE

cat filename | while read line
do
echo $line
done

注释:当遇见管道的时候管道左边的命令的输出会作为管道右边命令的输入然后被输入出来。

 

方法3    for  循环。

for  line  in  `cat filename`
do
echo ${line}
done

注释:这种方式是通过for循环的方式来读取文件的内容相比大家很熟悉了,这里不多说。

 

在各个方法中,for语句效率最高,而在while循环中读写文件时,第一种方式执行效率最高。

 

for逐行读和while逐行读是有区别的,如:

$ cat t.txt
1111
2222
3333 4444 555

$ cat t.txt | while read line; do echo ${line}; done
1111
2222
3333 4444 555

$ for line in `cat t.txt`; do echo ${line}; done
1111
2222
3333
4444
555

Shell逐行读取文件的3种方法

原文:http://www.cnblogs.com/mgzc-1508873480/p/7866915.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!