shell脚本,按行读取文件的几种方法。


第一种方法用while实现按读取文件。
[root@localhost wyb]# cat a.txt 第一行 aaaaaa 第二行 bbbbbb 第三行 cccccc 第四行 dddddd 第五行 eeeeee [root@localhost wyb]# cat anhang.sh #!/bin/bash cat a.txt| while read line do echo $line sleep 1 done [root@localhost wyb]# bash anhang.sh 第一行 aaaaaa 第二行 bbbbbb 第三行 cccccc 第四行 dddddd 第五行 eeeeee [root@localhost wyb]# [root@localhost wyb]# cat anhang.sh #!/bin/bash while read line do echo $line sleep 1 done<a.txt [root@localhost wyb]# bash anhang.sh 第一行 aaaaaa 第二行 bbbbbb 第三行 cccccc 第四行 dddddd 第五行 eeeeee [root@localhost wyb]# [root@localhost wyb]# cat a.txt 第一行 aaaaaa 第二行 bbbbbb 第三行 cccccc 第四行 dddddd 第五行 eeeeee

#第二种方法用for循环来按行读取文件,注意:用for有一个小bug,不是一行一行来读,是按空格来分。(如果一整行没有空格,就会正常显示。) [root@localhost wyb]#
cat foranhang.sh #!/bin/bash for line in `cat a.txt` do echo $line sleep 1 done [root@localhost wyb]# bash foranhang.sh 第一行 aaaaaa 第二行 bbbbbb 第三行 cccccc 第四行 dddddd 第五行 eeeeee [root@localhost wyb]#
原文地址:https://www.cnblogs.com/wangyuebo/p/5824976.html