码迷,mamicode.com
首页 > 系统相关 > 详细

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

时间:2017-11-20 17:53:13      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:file   内容   输入   col   读写   cat   read   执行文件   filename   

方法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种方法

标签:file   内容   输入   col   读写   cat   read   执行文件   filename   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!