Linux SHELL 读取文件的每一行内容并输出

napoleon · 2022-05-10 22:58:59 · 热度: 15

假设读取的文件为当期目录下的 test.txt 文件,内容如下:

Google 
Codercto
Taobao

实例 1

#!/bin/bash

while read line
do
    echo $line
done < test.txt

执行输出结果为:

Google
Codercto
Taobao

实例 2

#!/bin/bash

cat test.txt | while read line
do
    echo $line
done

执行输出结果为:

Google
Codercto
Taobao

实例 3

for line in `cat  test.txt`
do
    echo $line
done

执行输出结果为:

Google
Codercto
Taobao

for 逐行读和 while 逐行读是有区别的,如:

$ cat test.txt
Google
Codercto
Taobao

$ cat test.txt | while read line; do echo $line; done
Google
Codercto
Taobao


$ for line in $(<test.txt); do echo $line; done
Google
Codercto
Taobao

猜你喜欢:
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册