在linux中有很多方法逐行读取一个文件的方法,其中最常用的就是下面的脚本里的方法,而且是效率最高,使用最多的方法。为了给大家一个直观的感受,我们将通过生成一个大的文件的方式来检验各种方法的执行效率。方法1:while循环中执行效率最高,最常用的方法。
function while_read_line_bottm(){
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
exec 0<&<3
}
注释: 这种方法分2步骤,第一,通过将所有内容重定向到文件描述符3来关闭文件描述符0.为此我们用了语法exec 3 $timefile
script=$(basename $0)
function usage(){
echo -e \nusage: $script file \n
exit 1
}
function while_read_bottm(){
while read line
do
echo $line
done < $filename
}
function while_read_line(){
cat $filename | while read line
do
echo $line
done
}
function while_read_line_fd(){
exec 3<&0
exec 0< $filename
while read line
do
echo $line
done
exec 0> $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
do
echo $line
done < $filename
方式执行效率最高。
保持现代工业自动化嗡嗡声的 3 种产品
智能手机新江湖时代:微软收购诺基亚
扩张MEMS业务版图 歌尔加快传感器和SiP模组布局
智能镜子显示屏的应用,让我们的生活更加便捷
旋转变压器软件解码方案(2)
Linux shell逐行读取文件的方法
测量仪器中的各种波形抽取方式
传感器公司排队IPO,持续经营能力获证监会重点关注
小米电视4C 50英寸:主打人工智能语音,采用4K超高清屏
鸿蒙系统搭载国产家电,会产生什么样的效果呢?
EDA实际应用的典型小案例
Al想要充分赋能心血管领域 有“两道门槛”需跨越
痛失香港首富宝座的宁德时代背景吓人?竟是日本传感器龙头TDK!
RAID原理_不同级别RAID的优缺点
使用Synopsys VIP签署PCIe 5.0验证
基于串口透明传输的无线射频收发系统设计
面向智能家居的物联网该如何解决
高通收购NUVIA,剑指CPU市场
探秘浪潮智能化存储管理平台InView的极致管理能力
期货现货交易所内盘外盘系统开发公司