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循环 的方式输出有点特别:(每一个空格切分 对应 一行输出)

原文地址:https://www.cnblogs.com/DreamDrive/p/7522678.html