脚本实现查找给定后缀的文件

问题场景

用脚本实现在一个文件夹下寻找给定后缀的所有文件。

脚本一

#!/bin/sh  
#非递归
#============ get the file name ===========  
echo -e "请输入你要读取的文件夹路径\n当前路径为${PWD}"  
read InputDir
#判断输入路径是不是目录  
if [ -d ${InputDir} ];
    then 
    echo "你输入的文件夹路径为${InputDir}"  
    echo -e "请输入你要将数据输出保存的文件路径\n当前路径为${PWD}"  
    read OutputFile    
    echo "输出保存的文件路径为${OutputFile}"  
    : > ${OutputFile}   #清空OutputFile  
    echo -e "请输入要匹配文件后缀名"
    read tarPostfix
    #循环读取文件夹名  
    for file_a in ${InputDir}/*;
    do  
        temp_file=`basename $file_a`  
        full_path="`pwd`/${temp_file}"
        postfix=${full_path#*.}    #获得后缀名
        if [[ ${temp_file} = ${OutputFile} || ${full_path} = ${OutputFile} ]]; #跳过目标输出文件
            then
            continue
        else
            if [ ${postfix} = ${tarPostfix} ];
                then 
                echo "${full_path}" >> $OutputFile
            else
                continue
            fi
        fi
    done
    echo
    #判断目标文件存在不
    if [[ -f ${OutputFile} && `stat -c%s ${OutputFile}` -gt 0 ]];
        then
        echo "成功找到匹配的文件如下"
        echo `cat ${OutputFile}`
    else
        echo "没有找到匹配的文件"
    fi
else
    echo "您输入的目录不存在,尝试判断是不是文件..."
    if [ -f ${InputDir} ];
        then
        echo "您输入的文件路径为${InputDir}" 
        echo -e "请输入要匹配文件后缀名"
        read tarPostfix
        temp_file=`basename ${InputDir}`  
        full_path="`pwd`/${temp_file}"
        postfix=${full_path#*.}    #获得后缀名
        echo
        if [ ${postfix} = ${tarPostfix} ];
            then
            echo "匹配成功,绝对路径:${full_path}" 
        else
            echo "该文件没有匹配成功"
        fi
    else
        echo
        echo "您输入的文件不存在"
    fi
fi  

脚本二

#!/bin/sh  
#递归
#============ get the file name ===========  
echo -e "请输入你要读取的文件夹路径\n当前路径为${PWD}"  
read InputDir  
echo "你输入的文件夹路径为${InputDir}"  
echo -e "请输入你要将数据输出保存的文件路径\n当前路径为${PWD}"  
read OutputFile    
echo "输出保存的文件路径为${OutputFile}" 
echo -e "请输入匹配的后缀"  
read postfix
: > ${OutputFile}   #清空OutputFile  
#递归读取文件夹 
if [ -d ${InputDir} ];
    then
    find ${InputDir} -name '*.'${postfix} > ${OutputFile}
    size=stat -c%s ${OutputFile}
    if [ size = 0 ];
        then
        echo '没有找到匹配的文件'
    elif [ size > 0 ];
        then
        echo '匹配成功,文件如下:'
        echo `cat ${OutputFile}`
    fi
else
    echo '目录不存在'
fi
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值