有的时候,处理文件真是一层目录包含一层目录的,即使是用脚本处理,如果不使用递归处理目录的方法,也会很麻烦。今天就来介绍一下如何在Linux下使用shell脚本递归的遍历一个目录。
-
1、tree.sh
其中的两个全局变量用来验证是否处理正确,应和系统命令tree统计出来的结果相对应。[root@master dancicizu]# cat tree.sh #! /bin/sh #number of directories and files DS=0 FS=0 #1st param, the dir name #2nd param, the aligning space function listFiles(){ for file in `ls "$1"` do if [ -d "$1/${file}" ];then echo "$2${file}" ((DS++)) listFiles "$1/${file}" " $2" else echo "$2${file}" ((FS++)) fi done } listFiles $1 " " echo "${DS} dictories,${FS} files"
-
2、测试
这里,我新建了test目录,此目录下还有多层目录。#首先使用系统命令tree来打印此目录的层级关系 [root@master dancicizu]# tree test/ test/ ├── a.txt ├── b.txt ├── C │ └── E │ └── F └── D ├── e.txt └── f.txt 4 directories, 4 files #然后使用自写tree.sh脚本来打印此目录的层级关系 [root@master dancicizu]# ./tree.sh test a.txt b.txt C E F D e.txt f.txt 4 dictories,4 files
-
3、应用
有了递归遍历目录的脚本方法,我们就可以方便的进行许多处理工作了,比如,批量递归的对一个目录进行dos2unix转换:[root@master dancicizu]# cat tree.sh [root@master dancicizu]# cat tree.sh #! /bin/sh #number of directories and files DS=0 FS=0 #1st param, the dir name #2nd param, the aligning space function listFiles(){ for file in `ls "$1"` do if [ -d "$1/${file}" ];then #echo "$2${file}" ((DS++)) listFiles "$1/${file}" " $2" else #echo "$2${file}" dos2unix "$1/${file}" ((FS++)) fi done } listFiles $1 " " echo "${DS} dictories,${FS} files" [root@master dancicizu]# ./tree.sh test [root@master dancicizu]# ./tree.sh test/ dos2unix: converting file test//a.txt to UNIX format ... dos2unix: converting file test//b.txt to UNIX format ... dos2unix: converting file test//D/e.txt to UNIX format ... dos2unix: converting file test//D/f.txt to UNIX format ... 4 dictories,4 files
再比如,递归解压7z文件:
#! /bin/sh #number of directories and files DS=0 FS=0 #1st param, the dir name #2nd param, the aligning space function listFiles(){ for file in `ls "$1"` do if [ -d "$1/${file}" ];then # echo "$2${file}" ((DS++)) listFiles "$1/${file}" "$2" else # echo "echo "$2${file}"" # nn=$(echo "$1/${file}" | tr -t '/' '-' | tr -t ' ' '') # mv "$1/${file}" "${nn}" # dos2unix "$1/${file}" if [[ "${file}" =~ ".7z" ]];then echo "${file}" cd $1 #强制覆盖已经存在的同名文件 7za x -aoa "${file}" if [ $? == 0 ];then rm -f "${file}" fi cd - fi ((FS++)) fi done } listFiles $1 "" echo "${DS} dictories,${FS} files"
网友评论