以下文章来源于Linux就该这么学 ,作者逄增宝
专注于Linux运维技术培训,让您学习的每节课都有所收获,订阅本号后可每天获得最新Linux运维行业资讯、最实用的Linux免费教程以及独家Linux考证资料,三十多万技术小伙伴的选择,Linux就该这么学!
方法一、使用输入重定向
[root@localhost ~]# cat mycontent.txt
This is a sample file
We are going through contents
line by line
to understand
[root@localhost ~]# cat example1.sh
#!/bin/bash
while read rows
do
echo "Line contents are : $rows "
done < mycontent.txt
[root@localhost ~]# while read rows; do echo "Line contents are : $rows"; done < mycontent.txt
方法二、使用cat命令和管道符
cat
命令和管道符|
,然后使用管道符将其输出作为输入传送到while循环。[root@localhost ~]# cat example2.sh
#!/bin/bash
cat mycontent.txt | while read rows
do
echo "Line contents are : $rows "
done
|
管道符将cat输出的内容保存在"$rows"变量中。[root@localhost ~]# cat mycontent.txt |while read rows;do echo "Line contents are : $rows";done
方法三、使用传入的文件名作为参数
[root@localhost ~]# cat example3.sh
#!/bin/bash
while read rows
do
echo "Line contents are : $rows "
done < $1
<
从命令行参数$1
读取文件内容方法四、使用awk命令
[root@localhost ~]# cat example4.sh
#!/bin/bash
cat mycontent.txt |awk '{print "Line contents are: "$0}'
总结