XuLaLa.Tech

首页客户端下载Windows 使用V2Ray 教程SSR 教程Clash 教程

Bash脚本中逐行读取文件

2025.04.09

在编写bash脚本时,有时脚本必须逐行读取文件中的内容,这取决于自动化流程。在这里,我们学习bash脚本中逐行读取文件的3种方法。文章目录1 方法1:使用输入重定向器2 方法2:使用cat命令3 方法3: 使用作为参数传递的文件名4 处理反斜杠和转义字符5 总结方法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 处理流程:声明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 方法3: 使用作为参数传递的文件名第三种方法将通过命令行发送filename作为输入参数。创建名为“example3”的脚本文件。sh',如:$ more example3.sh

#!/bin/bash

while read y

do

echo "Line contents are : $y "

done 处理流程:声明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”变量而循环则逐行读取文件-r防止反斜杠转义被解释IFS(内部字段分隔符),如果我们想用字段分隔符拆分行,需要指定分隔符值(例如:如果行有'foo,bar'这样的值,并且想要拆分逗号,那么IFS值应该是(IFS=,))echo将帮助将内容打印到控制台一旦到达文件末尾,循环就会出现总结本教程通过示例解释了如何使用bash shell脚本逐行读取文件内容。它通过单独读取行来帮助搜索文件中的字符串。

© 2010-2022 XuLaLa 保留所有权利 本站由 WordPress 强力驱动
请求次数:69 次,加载用时:0.665 秒,内存占用:32.19 MB