shell遍历文件夹读取文件夹下的文件
collect_time.sh脚本需求:
遍历/dz目录下所有以A开头的文件夹,读取该文件夹下的time.log的首行内容,依次写入脚本的路径参数/lj/times.txt中。
编写collect_time.sh:
#!/bin/bash file="time.log" readDir="/dz" #$1是获取脚本的第一个参数/lj/times.txt paramPath=$1 #每次执行脚本前质空/lj/time.txt echo > $paramPath for df in `ls $readDir` do # -d $readDir"/"$df 判断是否是文件夹 if [ -d $readDir"/"$df ]; then # `echo $df|grep ^A`判断字符串首字母是否是A if [ `echo $df|grep ^A` ]; then #echo $$df # 判断是否是普通文件 if [ -f $readDir"/"$df"/"$file ]; then content=`head -n 1 $readDir"/"$df"/"$file` echo $df":"$content >> $paramPath fi fi fi done
(1)执行. collect_time.sh /lj/times.txt
(2)得到/lj/times.txt结果内容:
A_0:2021-03-13
A_1:2021-03-14
A_00:2021-03-13