如何在 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
運行結果:
如何工作的:
-
- 開始 while 循環,並在變量 “rows” 中保存每一行的內容
-
- 使用 echo 顯示輸出內容,$rows 變量爲文本文件中的每行內容
-
- 使用 echo 顯示輸出內容,輸出內容包括自定義的字符串和變量,$rows 變量爲文本文件中的每行內容
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
運行結果:
如何工作的:
-
- 使用管道將 cat 命令的輸出作爲輸入發送到 while 循環。
-
-
|
管道符將 cat 輸出的內容保存在 "$rows" 變量中。 -
- 使用 echo 顯示輸出內容,輸出內容包括自定義的字符串和變量,$rows 變量爲文本文件中的每行內容
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
運行結果:
如何工作的:
-
- 開始 while 循環,並在變量 “rows” 中保存每一行的內容
-
- 使用 echo 顯示輸出內容,$rows 變量爲文本文件中的每行內容
-
- 使用輸入重定向
<
從命令行參數$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