Shell 逐行读取单个文件或者多个文件内容

限于喜欢 提交于 2020-03-31 01:16:14

[root@zt94886 ~]# less 1.txt
asdc
sadca

asdc
方式1:while循环逐行读取文件内容
#!/bin/bash
cat ./1.txt | while read line; do
echo $line
done
方式2:while循环逐行读取文件内容
#!/bin/bash
while read LINE; do
echo $line
done < ./1.txt
执行结果:
[root@zt94886 ~]# sh 1.sh
asdc
sadca

asdc

方式3:for循环批量读取多个文件内容:
[root@zt94886 /script/day/var]# ls
1.txt 2.txt 3.txt
[root@zt94886 /script/day/var]# pwd
/script/day/var

[root@zt94886 ~]# less /script/day/var/1.txt
asdcasd
asdcasdc
asdcasdc
asdcasdc
asdcasdc
asdcasdc
asdcasdc

[root@zt94886 ~]# less /script/day/var/2.txt
12123
123123
123123

[root@zt94886 ~]# less /script/day/var/3.txt
asdc asdc
sadcasdc
asdcasdc asdcasdc asdcawdc

asdc
asdcasdcasdc

asdcasdcasdc

asdcasdcasdc

#!/usr/bin/bash
cd /script/day/var/
for i in $(ls *)
do
cat $i | while read line
do
echo $line
done

done

执行结果:
[root@zt94886 ~]# sh for.sh
asdcasd
asdcasdc
asdcasdc
asdcasdc
asdcasdc
asdcasdc
asdcasdc

12123
123123
123123

asdc asdc
sadcasdc
asdcasdc asdcasdc asdcawdc

asdc
asdcasdcasdc

asdcasdcasdc

asdcasdcasdc

注意:使用For循环逐行读取文件时,For循环取值列表是以空白符或者TAB分割,针对空行,For循环会忽略,而While循环,针对空行还会输出。初学Shell,难免有错误之处,欢迎指正!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!