Shell逐行讀取檔案的4種方法

2022-08-16 22:12:14 字數 2916 閱讀 5129

這篇文章主要介紹了shell逐行讀取檔案的4種方法,本文介紹了while迴圈法、重定向法、管道法、檔案描述符法等一些方法,需要的朋友可以參考下

在linux中有很多方法逐行讀取乙個檔案的方法,其中最常用的就是下面的指令碼裡的方法,而且是效率最高,使用最多的方法。為了給大家乙個直觀的感受,我們將通過生成乙個大的檔案的方式來檢驗各種方法的執行效率。

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

複製**

**如下:

function while_read_line_bottm()

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

方法2 : 重定向法;管道法: cat $filename | while read line

複製**

**如下:

function while_read_line()

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

方法3: 檔案描述符法

複製**

**如下:

function while_read_line_fd()

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

方法4    for  迴圈。

複製**

**如下:

function  for_in_file()

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

首先我們用指令碼(指令碼見附件)生成乙個70000行的檔案,檔案位置在/scripts/bigfile。然後通過下面的指令碼來測試各個方法的執行效率,指令碼很簡單,不再解釋。

複製**

**如下:

#!/bin/bash

filename="$1"

timefile="/tmp/loopfile.out" > $timefile

script=$(basename $0)

function usage()

function while_read_bottm()

function while_read_line()

function while_read_line_fd()

function for_in_file()

if [ $# -lt 1 ] ; then

usage

fiecho -e " \n starting file processing of each method\n"

echo -e "method 1:"

echo -e "function while_read_bottm"

time while_read_bottm >> $timefile

echo -e "\n"

echo -e "method 2:"

echo -e "function while_read_line "

time while_read_line >> $timefile

echo -e "\n"

echo -e "method 3:"

echo "function while_read_line_fd"

time while_read_line_fd >>$timefile

echo -e "\n"

echo -e "method 4:"

echo -e "function  for_in_file"

time  for_in_file >> $timefile

執行指令碼後: [root@localhost shell]# ./while /scripts/bigfile

指令碼輸出內容:

複製**

**如下:

method 1:

function while_read_bottm

real    0m5.689s

user    0m3.399s

sys    0m1.588s

method 2:

function while_read_line

real    0m11.612s

user    0m4.031s

sys    0m4.956s

method 3:

function while_read_line_fd

real    0m5.853s

user    0m3.536s

sys    0m1.469s

method 4:

function  for_in_file

real    0m5.153s

user    0m3.335s

sys    0m1.593s

下面我們對各個方法按照速度進行排序。

複製**

**如下:

real    0m5.153s    method 4 (for 迴圈法)

real    0m5.689s    method 1  (while 釜底抽薪法)

real    0m5.853s    method 3    (識別符號法)

real    0m11.612s  method 2    (管道法)

由此可見在各個方法中,for語句效率最高,而在while迴圈中讀寫檔案時,

複製**

**如下:

while read line

doecho $line

done < $filename

方式執行效率最高。

Shell指令碼逐行讀取檔案

方法1 while迴圈中執行效率最高,最常用的方法。while read line doecho line done filename 注釋 這種方式在結束的時候需要執行檔案,就好像是執行完的時候再把檔案讀進去一樣。方法2 管道法 cat filename while read line cat f...

shell 逐行讀取檔案的內容

說明 shell 逐行讀取文字檔案內容。示例 讀取 etc passwd 檔案內容。1 python view plain copy bin bash ifs n 0 forline in cat etc passwd do n expr n 1 echo e n t line done 2 pyt...

Shell逐行讀取檔案的3種方法

方法1 while迴圈中執行效率最高,最常用的方法。while read line doecho line done filename 注釋 這種方式在結束的時候需要執行檔案,就好像是執行完的時候再把檔案讀進去一樣。方法2 管道法 cat filename while read line cat f...