shell 逐行读取文件

方法一:重定向法

该方式使用最普遍,也是执行效率最高的

编辑示例脚本 example.sh :

#! /bin/bash

FILENAME=test.txt

while read line
do
        echo $line
done < ${FILENAME}

执行输出:

$ bash example.sh 
one
two
three
four
five
six seven eight nine

方法二: 管道法

编辑示例脚本 example.sh :

#! /bin/bash

FILENAME=test.txt

cat ${FILENAME} | while read line
do
        echo $line
done

运行脚本:

$ bash example.sh
one
two
three
four
five
six seven eight nine

方法三:for 循环

for循环是很常用的

编辑示例脚本 example.sh :

#! /bin/bash

FILENAME=test.txt

for line in $(cat ${FILENAME})
do
        echo $line
done

运行脚本:

$ bash example.sh
one
two
three
four
five
six
seven
eight
nine

适用范围仅限于一行只有一个元素

一行多个元素,则可能达不到预期

相关文章

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注