Shell逐行读取文件的4种方法
在Linux中有很多方法逐行读取一个文件的方法,其中最常用的就是下面的脚本里的方法,而且是效率最高,使用最多的方法。为了给大家一个直观的感受,我们将通过生成一个大的文件的方式来检验各种方法的执行效率。
方法1:while循环中执行效率最高,最常用的方法。
functionwhile_read_LINE_bottm(){
WhilereadLINE
do
echo$LINE
done <$FILENAME
}
注释:我习惯把这种方式叫做read釜底抽薪,因为这种方式在结束的时候需要执行文件,就好像是执行完的时候再把文件读进去一样。
方法2:重定向法;管道法:cat$FILENAME|whilereadLINE
FunctionWhile_read_LINE(){
cat$FILENAME|whilereadLINE
do
echo$LINE
done
}
注释:我只所有把这种方式叫做管道法,相比大家应该可以看出来了吧。当遇见管道的时候管道左边的命令的输出会作为管道右边命令的输入然后被输入出来。
方法3:文件描述符法
Functionwhile_read_line_fd(){
Exec3<&0
Exec0<$FILENAME
WhilereadLINE
Do
Echo$LINE
Exec0<&<3
}
注释:这种方法分2步骤,第一,通过将所有内容重定向到文件描述符3来关闭文件描述符0.为此我们用了语法Exec3<&0。第二部将输入文件放送到文件描述符0,即标准输入。
方法4 for 循环。
function for_in_file(){
For i in `cat$FILENAME`
do
echo$i
done
}
注释:这种方式是通过for循环的方式来读取文件的内容相比大家很熟悉了,这里不多说。对各个方法进行测试,看那方法的执行效率最高。
首先我们用脚本(脚本见附件)生成一个70000行的文件,文件位置在/scripts/bigfile。然后通过下面的脚本来测试各个方法的执行效率,脚本很简单,不再解释。
#!/bin/bash
FILENAME="$1"
TIMEFILE="/tmp/loopfile.out">$TIMEFILE
SCRIPT=$(basename$0)
functionusage(){
echo-e"\nUSAGE:$SCRIPTfile\n"
exit1
}
functionwhile_read_bottm(){
whilereadLINE
do
echo$LINE
done<$FILENAME
}
functionwhile_read_line(){
cat$FILENAME|whilereadLINE
do
echo$LINE
done
}
functionwhile_read_line_fd(){
exec3<&0
exec0<$FILENAME
whilereadLINE
do
echo$LINE
done
exec0<&3
}
functionfor_in_file(){
foriin `cat$FILENAME`
do
echo$i
done
}
if[$#-lt1];then
usage
fi
echo-e"\nstartingfileprocessingofeachmethod\n"
echo-e"method1:"
echo-e"functionwhile_read_bottm"
timewhile_read_bottm>>$TIMEFILE
echo-e"\n"
echo-e"method2:"
echo-e"functionwhile_read_line"
timewhile_read_line>>$TIMEFILE
echo-e"\n"
echo-e"method3:"
echo"functionwhile_read_line_fd"
timewhile_read_line_fd>>$TIMEFILE
echo-e"\n"
echo-e"method4:"
echo-e"function for_in_file"
time for_in_file>>$TIMEFILE
执行脚本后:[root@localhostshell]#./while/scripts/bigfile
脚本输出内容:
method1: functionwhile_read_bottm real 0m5.689s user 0m3.399s sys 0m1.588s method2: functionwhile_read_line real 0m11.612s user 0m4.031s sys 0m4.956s method3: functionwhile_read_line_fd real 0m5.853s user 0m3.536s sys 0m1.469s method4: function for_in_file real 0m5.153s user 0m3.335s sys 0m1.593s
下面我们对各个方法按照速度进行排序。
real 0m5.153s method4(for循环法) real 0m5.689s method1 (while釜底抽薪法) real 0m5.853s method3 (标识符法) real 0m11.612s method2 (管道法)
由此可见在各个方法中,for语句效率最高,而在while循环中读写文件时,
whilereadLINE do echo$LINE done<$FILENAME
方式执行效率最高。