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

安全 应用安全
本文介绍了如何使用shell脚本逐行读取文件内容,通过单独读取行,可以帮助搜索文件中的字符串。

[[394564]]

在这里,我们学习Shell脚本中的3种方法来逐行读取文件。

方法一、使用输入重定向

逐行读取文件的最简单方法是在while循环中使用输入重定向。

为了演示,在此创建一个名为“ mycontent.txt”的文本文件,文件内容在下面:

  1. [root@localhost ~]# cat mycontent.txt  
  2. This is a sample file 
  3. We are going through contents 
  4. line by line 
  5. to understand 

创建一个名为“ example1.sh”的脚本,该脚本使用输入重定向和循环:

  1. [root@localhost ~]# cat example1.sh  
  2. #!/bin/bash 
  3. while read rows 
  4. do 
  5.   echo "Line contents are : $rows " 
  6. done < mycontent.txt 

运行结果:

如何工作的:

  • - 开始while循环,并在变量“rows”中保存每一行的内容
  • - 使用echo显示输出内容,$rows变量为文本文件中的每行内容
  • - 使用echo显示输出内容,输出内容包括自定义的字符串和变量,$rows变量为文本文件中的每行内容

Tips:可以将上面的脚本缩减为一行命令,如下:

  1. [root@localhost ~]# while read rows; do echo "Line contents are : $rows"; done < mycontent.txt

方法二、使用cat命令和管道符

第二种方法是使用cat命令和管道符|,然后使用管道符将其输出作为输入传送到while循环。

创建脚本文件“ example2.sh”,其内容为:

  1. [root@localhost ~]# cat example2.sh  
  2. #!/bin/bash 
  3. cat mycontent.txt | while read rows 
  4. do 
  5.   echo "Line contents are : $rows " 
  6. done 

运行结果:

如何工作的:

- 使用管道将cat命令的输出作为输入发送到while循环。

- |管道符将cat输出的内容保存在"$rows"变量中。

- 使用echo显示输出内容,输出内容包括自定义的字符串和变量,$rows变量为文本文件中的每行内容

Tips:可以将上面的脚本缩减为一行命令,如下:

  1. [root@localhost ~]# cat mycontent.txt |while read rows;do echo "Line contents are : $rows";done 

方法三、使用传入的文件名作为参数

第三种方法将通过添加$1参数,执行脚本时,在脚本后面追加文本文件名称。

创建一个名为“ example3.sh”的脚本文件,如下所示:

  1. [root@localhost ~]# cat example3.sh  
  2. #!/bin/bash 
  3. while read rows 
  4. do 
  5.   echo "Line contents are : $rows " 
  6. done < $1 

运行结果:

如何工作的:

  • - 开始while循环,并在变量“rows”中保存每一行的内容
  • - 使用echo显示输出内容,$rows变量为文本文件中的每行内容
  • - 使用输入重定向<从命令行参数$1读取文件内容

方法四、使用awk命令

通过使用awk命令,只需要一行命令就可以逐行读取文件内容。

创建一个名为“ example4.sh”的脚本文件,如下所示:

  1. [root@localhost ~]# cat example4.sh  
  2. #!/bin/bash 
  3.  
  4. cat mycontent.txt |awk '{print "Line contents are: "$0}' 

运行结果:

总结

本文介绍了如何使用shell脚本逐行读取文件内容,通过单独读取行,可以帮助搜索文件中的字符串。

 

责任编辑:武晓燕 来源: Linux就该这么学
相关推荐

2021-08-20 10:46:25

Shell脚本文件Linux

2016-12-20 09:30:22

shell脚本linux

2016-12-16 09:23:29

LinuxShell脚本

2023-01-15 17:11:44

Rust

2021-02-15 17:29:46

LinuxShell脚本

2021-08-30 07:50:42

脚本语言命令行

2022-11-03 08:13:52

echo 命令Linux

2022-11-01 15:38:22

LinuxShell

2012-05-08 10:51:10

Linuxshell脚本

2017-01-18 20:38:36

LinuxShell脚本命令

2018-02-01 17:32:30

LinuxUNIXBash Shell

2023-04-04 07:52:26

RedisLua脚本

2022-01-14 09:10:56

C++文件Linux

2021-03-14 09:28:24

Linux Shell脚本

2022-12-22 20:47:01

脚本循环结构

2022-10-09 10:18:44

LinuxShell脚本

2017-12-18 10:12:48

LinuxShell命令

2023-10-19 14:52:27

2021-01-18 17:23:30

代码调试VS Code

2021-07-02 06:54:44

Shell脚本 Linux
点赞
收藏

51CTO技术栈公众号