教程集 www.jiaochengji.com
教程集 >  脚本编程  >  shell  >  正文 shell脚本递归遍历目录与子目录的例子

shell脚本递归遍历目录与子目录的例子

发布时间:2014-12-17   编辑:jiaochengji.com
本文介绍了shell脚本递归遍历目录及子目录的例子,有关shell脚本递归遍历目录的方法,有需要的朋友参考下。

使用shell脚本递归遍历目录,脚本实现递归遍历指定目录,打印目录下的文件名。

例1:
 

复制代码 代码示例:

#!/bin/sh
# www.jiaochengji.com
#
function scandir() {
    local cur_dir parent_dir workdir
    workdir=$1
    cd ${workdir}
    if [ ${workdir} = "/" ]
    then
        cur_dir=""
    else
        cur_dir=$(pwd)
    fi

    for dirlist in $(ls ${cur_dir})
    do
        if test -d ${dirlist};then
            cd ${dirlist}
            scandir ${cur_dir}/${dirlist}
            cd ..
        else
            echo ${cur_dir}/${dirlist}
        fi
    done
}

if test -d $1
then
    scandir $1
elif test -f $1
then
    echo "you input a file but not a directory,pls reinput and try again"
    exit 1
else
    echo "the Directory isn't exist which you input,pls input a new one!!"
    exit 1
fi

例2:递归读取目录及其子目录
#! /bin/bash
# www.jiaochengji.com
#
function read_dir(){
    for file in `ls $1`
    do
        if [ -d $1"/"$file ]  //注意此处之间一定要加上空格,否则会报错
        then
            read_dir $1"/"$file
        else
            echo $1"/"$file
        fi
    done
}
#测试目录 test
read_dir test

为test.sh加上执行权限即可执行:
chmod +x test.sh
sh test.sh

到此即可通过传递参数来读取目录文件了。

例3,递归实现各个子目录孙目录。
#!/bin/bash
# www.jiaochengji.com
#modify.func
doit()   //处理当前目录下的非目录文件,忽略目录文件
{
    oldname=`ls | grep "$1$"`
    for name in $oldname
    do
       if [ -d "$name" ]
       then :
       else
            basename=`echo $name | awk -F "." '{print $1}'` 
            newname="$basename$2"                                      
            echo -e "$PWD/$name\t\t$newname"
            mv $name $newname
            count=`expr ${count} + 1`
       fi
    done
    return 0
}
do_recursive()          //从当前目录开始,递归处理各目录
{
    doit $1 $2
    for filename in `ls`
    do
         if [ -d "$filename" ]
         then
             cd $filename
             do_recursive $1 $2
             cd ..
         fi
    done
    return 0
}
modify() //处理当前目录,并报告结果,这个相当于主函数,也可以直接调用do_recursive
{
    PARAMS=2
    if [ $# -ne $PARAMS ]
    then
        echo "usage: mv_to .suf1 .suf2"
        return 1
    fi
    count=0
    do_recursive $1 $2
    echo "complete! $count files have been modified."
    return 0
}

您可能感兴趣的文章:
php无限遍历目录代码
shell脚本递归遍历目录与子目录的例子
PHP遍历文件和文件夹的小例子
PHP删除N分钟前创建的所有文件的小例子
php 读取目录文件夹列表的例子
查找目录及子目录中同名文件的shell脚本(图文)
递归修改目录与文件名统一为小写的shell脚本
PHP遍历目录下所有文件的小例子
用PHP实现遍历删除目录及此目录下存放的所有文件
php目录遍历与删除的代码一例

关键词: 遍历目录  递归查询   
[关闭]
~ ~