共计 1446 个字符,预计需要花费 4 分钟才能阅读完成。
导读 | 在这里,我们学习 Shell 脚本中的 3 种方法来逐行读取文件。 |
方法一、使用输入重定向
逐行读取文件的最简单方法是在 while 循环中使用输入重定向。
为了演示,在此创建一个名为“mycontent.txt”的文本文件,文件内容在下面:
[ | ]|
This is a sample file | |
We are going through contents | |
line by line | |
to understand |
创建一个名为“example1.sh”的脚本,该脚本使用输入重定向和循环:
[root@localhost ~]# cat example1.sh | |
#!/bin/bash | |
while read rows | |
do | |
echo "Line contents are : $rows" | |
done | |
运行结果: | |
如何工作的: |
- – 开始 while 循环,并在变量“rows”中保存每一行的内容
- – 使用 echo 显示输出内容,$rows 变量为文本文件中的每行内容
- – 使用 echo 显示输出内容,输出内容包括自定义的字符串和变量,$rows 变量为文本文件中的每行内容
Tips:可以将上面的脚本缩减为一行命令,如下:
[root@localhost ~]# while read rows; do echo "Line contents are : $rows"; done | |
方法二、使用 cat 命令和管道符 | |
第二种方法是使用 cat 命令和管道符|,然后使用管道符将其输出作为输入传送到 while 循环。 | |
创建脚本文件“example2.sh”,其内容为: | |
[root@localhost ~]# cat example2.sh | |
#!/bin/bash | |
cat mycontent.txt | while read rows | |
do | |
echo "Line contents are : $rows" | |
done | |
运行结果: | |
如何工作的: | |
– 使用管道将 cat 命令的输出作为输入发送到 while 循环。 | |
– |管道符将 cat 输出的内容保存在 ”$rows” 变量中。 | |
– 使用 echo 显示输出内容,输出内容包括自定义的字符串和变量,$rows 变量为文本文件中的每行内容 | |
Tips:可以将上面的脚本缩减为一行命令,如下: | |
[root@localhost ~]# cat mycontent.txt |while read rows;do echo "Line contents are : $rows";done | |
方法三、使用传入的文件名作为参数 | |
第三种方法将通过添加 $1 参数,执行脚本时,在脚本后面追加文本文件名称。 | |
创建一个名为“example3.sh”的脚本文件,如下所示: | |
[root@localhost ~]# cat example3.sh | |
#!/bin/bash | |
while read rows | |
do | |
echo "Line contents are : $rows" | |
done | |
运行结果: | |
如何工作的: | |
– 开始 while 循环,并在变量“rows”中保存每一行的内容 | |
– 使用 echo 显示输出内容,$rows 变量为文本文件中的每行内容 | |
– 使用输入重定向 从命令行参数 $1 读取文件内容 | |
方法四、使用 awk 命令 | |
通过使用 awk 命令,只需要一行命令就可以逐行读取文件内容。 | |
创建一个名为“example4.sh”的脚本文件,如下所示: | |
[root@localhost ~]# cat example4.sh | |
#!/bin/bash | |
cat mycontent.txt |awk '{print"Line contents are: "$0}' | |
运行结果: | |
总结 | |
本文介绍了如何使用 shell 脚本逐行读取文件内容,通过单独读取行,可以帮助搜索文件中的字符串。 |
正文完
星哥玩云-微信公众号
