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,难免有错误之处,欢迎指正!