[[email protected] ~]# 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
执行结果:
[[email protected] ~]# sh 1.sh
asdc
sadca
asdc
方式3:for循环批量读取多个文件内容:
[[email protected] /script/day/var]# ls
1.txt 2.txt 3.txt
[[email protected] /script/day/var]# pwd
/script/day/var
[[email protected] ~]# less /script/day/var/1.txt
asdcasd
asdcasdc
asdcasdc
asdcasdc
asdcasdc
asdcasdc
asdcasdc
[[email protected] ~]# less /script/day/var/2.txt
12123
123123
123123
[[email protected] ~]# 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
执行结果:
[[email protected] ~]# 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,难免有错误之处,欢迎指正!
原文地址:https://blog.51cto.com/14648383/2483238