Linux shell逐行讀取文件的方法


方法1:while循環中執行效率最高,最常用的方法。

function while_read_line_bottom(){
    while read line
    do
        echo $line
    done  < $FILENAME
}

 

注釋:我習慣把這種方式叫做read釜底抽薪,因為這種方式在結束的時候需要執行文件,就好像是執行完的時候再把文件讀進去一樣。

方法2 : 重定向法;管道法: cat $FILENAME | while read LINE

function while_read_line(){
    cat $FILENAME | while read line
    do
        echo $line
    done
}

 

注釋:我只所有把這種方式叫做管道法,相比大家應該可以看出來了吧。當遇見管道的時候管道左邊的命令的輸出會作為管道右邊命令的輸入然后被輸入出來。

方法3: 文件描述符法

function while_read_line_fd(){
    exec 3<&0
    exec 0< $FILENAME
    while read line
    do
        echo $line
    done
    exec 0<&3
}

 

注釋: 這種方法分2步驟,第一,通過將所有內容重定向到文件描述符3來關閉文件描述符0.為此我們用了語法Exec 3<&0 。第二部將輸入文件放送到文件描述符0,即標准輸入。

方法4    for循環。

function for_in_file(){
    for i in  `cat $FILENAME`
    do
        echo $i
    done
}

 

注釋:這種方式是通過for循環的方式來讀取文件的內容相比大家很熟悉了,這里不多說。對各個方法進行測試,看那方法的執行效率最高。

調用測試這4種方法:

以上4個方法分別對應一個腳本文件,也可以把4種方法都寫在一個腳本文件中。

fun-while_read_line_bottom.sh

fun-while_read_line.sh

fun-while_read_line_fd.sh

fun-for_in_file.sh

然后寫一個測試腳本:

callfun.sh 內容如下:

#!/bin/bash
FILENAME="$1"

source fun-while_read_line_bottom.txt
source fun-while_read_line.txt
source fun-while_read_line_fd.txt
source fun-for_in_file.txt
echo " 方法1:while_read_line_bottom:輸出"
while_read_line_bottom $1
echo "方法2:while_read_line:輸出"
while_read_line $1
echo "方法3:while_read_line_fd:輸出"
while_read_line_fd $1
echo "方法4:for_in_file:輸出"
for_in_file $1

 

找一個要打印輸出的文件:

content.sh 內容如下:

Dark light, just light each other. The responsibility that you and my shoulders take together, such as 
one dust covers up. Only afraid the light suddenly put out in theendless dark night and countless loneliness.

 

運行腳本:(以上文件都放到了/root/fun/目錄下)

callfun.sh /root/fun/content.sh

其中方法4 for循環 的方式輸出有點特別:(每一個空格切分 對應 一行輸出)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM