博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Linux shell逐行读取文件的方法
阅读量:6859 次
发布时间:2019-06-26

本文共 1660 字,大约阅读时间需要 5 分钟。

方法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/bashFILENAME="$1"source fun-while_read_line_bottom.txtsource fun-while_read_line.txtsource fun-while_read_line_fd.txtsource fun-for_in_file.txtecho " 方法1:while_read_line_bottom:输出"while_read_line_bottom $1echo "方法2:while_read_line:输出"while_read_line $1echo "方法3:while_read_line_fd:输出"while_read_line_fd $1echo "方法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循环 的方式输出有点特别:(每一个空格切分 对应 一行输出)

 

转载地址:http://jqtyl.baihongyu.com/

你可能感兴趣的文章
由浅入深学优化之like‘%%’坑爹写法
查看>>
部署Hadoop高性能集群
查看>>
Determine Hadoop Memory Configuration Settings
查看>>
解析ActionResult子类JsonResult
查看>>
6.cadence原理图下[原创]
查看>>
Javascript图片裁切
查看>>
Android -- Serializable和Parcelable需要注意的
查看>>
Apache -- phpmyadmin导入文件过大
查看>>
吐槽一下Activiti用户手册和一本书
查看>>
解读Web Page Diagnostics网页细分图
查看>>
Enterprise Solution 管理软件开发框架流程实战
查看>>
hibernate缓存机制详细分析
查看>>
Android 动画效果 及 自定义动画
查看>>
基于Servlet、JSP、JDBC、MySQL登录模块(包括使用的过滤器和配置)
查看>>
Python将文本生成二维码
查看>>
统计学习那些事
查看>>
XLT架构图(自己 画的)
查看>>
GitHub Top 100 简介
查看>>
C语言中链表任意位置怎么插入数据?然后写入文件中?
查看>>
文档对象模型DOM(二)
查看>>