如何在 Bash 腳本中逐行讀取文件 [3 Methods]

當寫一個 bash 腳本,取決於自動化流程,有時腳本必須逐行讀取文件中的內容。 在這裡,我們學習了 3 種方法 bash 逐行讀取文件的腳本。

方法 1:使用輸入重定向器

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

為了演示,我們創建了一個名為“mycontent.txt”的示例文件,並將在本教程中使用它。

$ 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

怎麼運行的:

– 聲明外殼是“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

方法二:使用cat命令

第二種方法是使用 cat 命令然後發送它的 輸出 作為 輸入 暫時 環形 使用 管道.

創建一個腳本文件“example2.sh”,內容為:

$ more example2.sh
#!/bin/bash
cat mycontent.txt | while read y

do
echo "Line contents are : $y "
done

怎麼運行的:

– 聲明外殼是“bash”
– 使用管道將 cat 命令的輸出作為輸入發送到 while 循環
“|” 並將行內容保存在變量“y”中
– 做一部分 while 循環(起點)
– 回顯打印,“$y”表示打印變量值,即行
– 關閉 while 循環完成

腳本和輸出的執行:

$ ./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. 使用作為參數傳遞的文件名

這第三種方法將發送文件名作為 輸入參數 通過命令行。

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

$ more example3.sh
#!/bin/bash
while read y
do
echo "Line contents are : $y "
done < $1

怎麼運行的:

– 聲明外殼是“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

處理反斜杠和轉義字符

當文件內容具有反斜杠和轉義字符時,讀取命令用於忽略這些反斜杠和轉義字符。

如果我們想從文件中讀取所有內容,請使用 -r 選項以防止反斜杠轉義被解釋並將值顯示到控制台中。

如果文件內容有逗號或管道等文件分隔符,我們可以使用 IFS(內部字段分隔符)根據分隔符拆分文件並顯示值。

示例外殼腳本:

#!/bin/bash
inputfile="foobar.txt"
while IFS=, read -r y
do
echo $y
done < $inputfile

腳本流程:

– 將文件路徑分配給“inputfile”變量
– While 循環逐行讀取文件
– -r 防止反斜杠轉義被解釋
– IFS(內部字段分隔符),如果我們想用字段分隔符分割行需要指定分隔符值(例如:如果行具有像’foo,bar’這樣的值並且想要分割逗號,那麼IFS值應該是( IFS=,))
– echo 將有助於將內容打印到控制台
– 一旦到達文件末尾而循環出來

結論

本教程解釋瞭如何使用 bash 帶有示例的 shell 腳本。 它通過單獨讀取行來幫助搜索文件中的字符串。

感謝閱讀,歡迎在評論區留下您的建議和評價。