如何在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腳本逐行讀取文件內容,通過單獨讀取行,可以幫助搜索文件中的字符串。