LinuxProbe 发表于 2021-7-13 20:21:49

如何在Shell脚本中逐行读取文件


在这里,我们学习Shell脚本中的3种方法来逐行读取文件。
方法一、使用输入重定向
逐行读取文件的最简单方法是在while循环中使用输入重定向。为了演示,在此创建一个名为“ mycontent.txt”的文本文件,文件内容在下面:# cat mycontent.txt This is a sample fileWe are going through contentsline by lineto understandhttps://www.linuxprobe.com/wp-content/uploads/2021/01/image1-6.png
创建一个名为“ example1.sh”的脚本,该脚本使用输入重定向和循环:# cat example1.sh #!/bin/bashwhile read rowsdoecho "Line contents are : $rows "done < mycontent.txt运行结果:
https://www.linuxprobe.com/wp-content/uploads/2021/01/image2-6.png
如何工作的:
[*]- 开始while循环,并在变量“rows”中保存每一行的内容
[*]- 使用echo显示输出内容,$rows变量为文本文件中的每行内容
[*]- 使用echo显示输出内容,输出内容包括自定义的字符串和变量,$rows变量为文本文件中的每行内容
Tips:可以将上面的脚本缩减为一行命令,如下:# while read rows; do echo "Line contents are : $rows"; done < mycontent.txthttps://www.linuxprobe.com/wp-content/uploads/2021/01/image3-7.png方法二、使用cat命令和管道符
第二种方法是使用cat命令和管道符|,然后使用管道符将其输出作为输入传送到while循环。创建脚本文件“ example2.sh”,其内容为:# cat example2.sh #!/bin/bashcat mycontent.txt | while read rowsdoecho "Line contents are : $rows "done运行结果:
https://www.linuxprobe.com/wp-content/uploads/2021/01/image4-6.png
如何工作的:
[*]- 使用管道将cat命令的输出作为输入发送到while循环。
[*]- |管道符将cat输出的内容保存在"$rows"变量中。
[*]- 使用echo显示输出内容,输出内容包括自定义的字符串和变量,$rows变量为文本文件中的每行内容
Tips:可以将上面的脚本缩减为一行命令,如下:# cat mycontent.txt |while read rows;do echo "Line contents are : $rows";donehttps://www.linuxprobe.com/wp-content/uploads/2021/01/image5-6.png方法三、使用传入的文件名作为参数
第三种方法将通过添加$1参数,执行脚本时,在脚本后面追加文本文件名称。创建一个名为“ example3.sh”的脚本文件,如下所示:# cat example3.sh #!/bin/bashwhile read rowsdoecho "Line contents are : $rows "done < $1运行结果:
https://www.linuxprobe.com/wp-content/uploads/2021/01/image6-4.png
如何工作的:
[*]- 开始while循环,并在变量“rows”中保存每一行的内容
[*]- 使用echo显示输出内容,$rows变量为文本文件中的每行内容
[*]- 使用输入重定向<从命令行参数$1读取文件内容
方法四、使用awk命令
通过使用awk命令,只需要一行命令就可以逐行读取文件内容。创建一个名为“ example4.sh”的脚本文件,如下所示:# cat example4.sh #!/bin/bashcat mycontent.txt |awk '{print "Line contents are: "$0}'运行结果:
https://www.linuxprobe.com/wp-content/uploads/2021/01/image7-3.png总结
本文介绍了如何使用shell脚本逐行读取文件内容,通过单独读取行,可以帮助搜索文件中的字符串。
页: [1]
查看完整版本: 如何在Shell脚本中逐行读取文件