如何在Shell腳本中逐行讀取文件
在這里,我們學(xué)習(xí)Shell腳本中的3種方法來逐行讀取文件。
方法一、使用輸入重定向
逐行讀取文件的最簡(jiǎn)單方法是在while循環(huán)中使用輸入重定向。
為了演示,在此創(chuàng)建一個(gè)名為“ mycontent.txt”的文本文件,文件內(nèi)容在下面:
- [root@localhost ~]# cat mycontent.txt
- This is a sample file
- We are going through contents
- line by line
- to understand
創(chuàng)建一個(gè)名為“ example1.sh”的腳本,該腳本使用輸入重定向和循環(huán):
- [root@localhost ~]# cat example1.sh
- #!/bin/bash
- while read rows
- do
- echo "Line contents are : $rows "
- done < mycontent.txt
運(yùn)行結(jié)果:
如何工作的:
- - 開始while循環(huán),并在變量“rows”中保存每一行的內(nèi)容
- - 使用echo顯示輸出內(nèi)容,$rows變量為文本文件中的每行內(nèi)容
- - 使用echo顯示輸出內(nèi)容,輸出內(nèi)容包括自定義的字符串和變量,$rows變量為文本文件中的每行內(nèi)容
Tips:可以將上面的腳本縮減為一行命令,如下:
- [root@localhost ~]# while read rows; do echo "Line contents are : $rows"; done < mycontent.txt
方法二、使用cat命令和管道符
第二種方法是使用cat命令和管道符|,然后使用管道符將其輸出作為輸入傳送到while循環(huán)。
創(chuàng)建腳本文件“ example2.sh”,其內(nèi)容為:
- [root@localhost ~]# cat example2.sh
- #!/bin/bash
- cat mycontent.txt | while read rows
- do
- echo "Line contents are : $rows "
- done
運(yùn)行結(jié)果:
如何工作的:
- 使用管道將cat命令的輸出作為輸入發(fā)送到while循環(huán)。
- |管道符將cat輸出的內(nèi)容保存在"$rows"變量中。
- 使用echo顯示輸出內(nèi)容,輸出內(nèi)容包括自定義的字符串和變量,$rows變量為文本文件中的每行內(nèi)容
Tips:可以將上面的腳本縮減為一行命令,如下:
- [root@localhost ~]# cat mycontent.txt |while read rows;do echo "Line contents are : $rows";done
方法三、使用傳入的文件名作為參數(shù)
第三種方法將通過添加$1參數(shù),執(zhí)行腳本時(shí),在腳本后面追加文本文件名稱。
創(chuàng)建一個(gè)名為“ example3.sh”的腳本文件,如下所示:
- [root@localhost ~]# cat example3.sh
- #!/bin/bash
- while read rows
- do
- echo "Line contents are : $rows "
- done < $1
運(yùn)行結(jié)果:
如何工作的:
- - 開始while循環(huán),并在變量“rows”中保存每一行的內(nèi)容
- - 使用echo顯示輸出內(nèi)容,$rows變量為文本文件中的每行內(nèi)容
- - 使用輸入重定向<從命令行參數(shù)$1讀取文件內(nèi)容
方法四、使用awk命令
通過使用awk命令,只需要一行命令就可以逐行讀取文件內(nèi)容。
創(chuàng)建一個(gè)名為“ example4.sh”的腳本文件,如下所示:
- [root@localhost ~]# cat example4.sh
- #!/bin/bash
- cat mycontent.txt |awk '{print "Line contents are: "$0}'
運(yùn)行結(jié)果:
總結(jié)
本文介紹了如何使用shell腳本逐行讀取文件內(nèi)容,通過單獨(dú)讀取行,可以幫助搜索文件中的字符串。