如何在 Shell 腳本中逐行讀取文件

在這裏,我們學習 Shell 腳本中的 3 種方法來逐行讀取文件。

方法一、使用輸入重定向

逐行讀取文件的最簡單方法是在 while 循環中使用輸入重定向。

爲了演示,在此創建一個名爲 “mycontent.txt” 的文本文件,文件內容在下面:

[root@localhost ~]# cat 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 < mycontent.txt

運行結果:

如何工作的:

Tips:可以將上面的腳本縮減爲一行命令,如下:

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

方法二、使用 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

運行結果:

如何工作的:

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 < $1

運行結果:

如何工作的:

方法四、使用 awk 命令

通過使用 awk 命令,只需要一行命令就可以逐行讀取文件內容。

創建一個名爲 “example4.sh” 的腳本文件,如下所示:

[root@localhost ~]# cat example4.sh 
#!/bin/bash

cat mycontent.txt |awk '{print "Line contents are: "$0}'

運行結果:

總結

本文介紹瞭如何使用 shell 腳本逐行讀取文件內容,通過單獨讀取行,可以幫助搜索文件中的字符串。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/03hzf4jxqOn6J0j71zzqQA