Bash脚本中逐行读取文件
嘻嘻发布于2022-05-10
最后更新于2022年5月11日
浏览在编写bash脚本时,有时脚本必须逐行读取文件中的内容,这取决于自动化流程。在这里,我们学习bash脚本中逐行读取文件的3种方法。
方法1:使用输入重定向器
逐行读取文件的最简单方法是在while循环中使用输入重定向器。
为了演示,我们创建了一个名为“mycontent”的示例文件。并将在本教程中使用它。
$ cat mycontent.txt
This is a sample file
We are going through contents
line by line
to understand
让我们创建一个名为“example1”的脚本。sh’使用输入重定向和循环。
$ more example1.sh
#!/bin/bash
while read y
do
echo "Line contents are : $y "
done < mycontent.txt
处理流程:
- 声明shell为“bash”
- 启动while循环并将行内容保存在变量“y”中
- 做while循环的一部分(起点)
- 回显打印,“$y”表示打印可变值,即行
- 使用输入重定向器“<”读取文件内容&使用“完成”关闭
脚本和输出的执行:
$ ./example1.sh
Line contents are : This is a sample file
Line contents are : We are going through contents
Line contents are : line by line
Line contents are : to understand
方法2:使用cat命令
第二种方法是使用cat命令,然后使用管道将其输出作为输入发送到while循环。
创建脚本文件“example2”。sh',内容如下:
$ more example2.sh
#!/bin/bash
cat mycontent.txt | while read y
do
echo "Line contents are : $y "
done
处理流程:
- 声明shell为“bash”
- 使用管道将cat命令的输出作为输入发送到while循环
- “|”并将行内容保存在变量“y”中
- 做while循环的一部分(起点)
- 回显打印,“$y”表示打印可变值,即行
- 在循环完成时关闭
脚本和输出的执行:
$ ./example2.sh
Line contents are : This is a sample file
Line contents are : We are going through contents
Line contents are : line by line
Line contents are : to understand
提示:我们可以组合所有命令,并将它们作为一行程序使用。
输出:
$ while read line; do echo $line; done < mycontent.txt
This is a sample file
We are going through contents
line by line
to understand
方法3: 使用作为参数传递的文件名
第三种方法将通过命令行发送filename作为输入参数。
创建名为“example3”的脚本文件。sh',如:
$ more example3.sh
#!/bin/bash
while read y
do
echo "Line contents are : $y "
done < $1
处理流程:
- 声明shell为“bash”
- 启动while循环并将行内容保存在变量“y”中
- 做while循环的一部分(起点)
- 回显打印,“$y”表示打印可变值,即行
- 从命令行参数中读取文件内容,即使用输入重定向器“<”读取$1,并以“完成”结束
脚本和输出的执行:
$ ./example3.sh mycontent.txt
Line contents are : This is a sample file
Line contents are : We are going through contents Output of Script
Line contents are : line by line
Line contents are : to understand
处理反斜杠和转义字符
当文件内容包含反斜杠和转义字符时,read命令用于忽略这些反斜杠和转义字符。
如果我们想读取文件中的所有内容,那么使用-r选项来防止反斜杠转义被解释,并在控制台中显示值。
如果文件内容有逗号或管道等文件分隔符,我们可以使用IFS(内部字段分隔符)根据分隔符拆分文件并显示值。
示例Shell脚本:
#!/bin/bash
inputfile="foobar.txt"
while IFS=, read -r y
do
echo $y
done < $inputfile
处理流程:
- 将文件路径分配给“inputfile”变量
- 而循环则逐行读取文件
- -r防止反斜杠转义被解释
- IFS(内部字段分隔符),如果我们想用字段分隔符拆分行,需要指定分隔符值(例如:如果行有'foo,bar'这样的值,并且想要拆分逗号,那么IFS值应该是(IFS=,))
- echo将帮助将内容打印到控制台
- 一旦到达文件末尾,循环就会出现
总结
本教程通过示例解释了如何使用bash shell脚本逐行读取文件内容。它通过单独读取行来帮助搜索文件中的字符串。