Shell循环列出目录下所有文件或查找目录下包含指定字符串的文件

19 篇文章 0 订阅

一、循环列出目录下所有文件

#!/bin/bash
function frfile()
{
    local basefolder=$1
    echo $basefolder
    #local filename
    for filename in $(ls $basefolder)
    do
        local fullpathfile=$basefolder/$filename
        if [ -d $fullpathfile ]
        then
            echo ======dir======
            ft=`ls $fullpathfile`
            if [ ! -z "$ft" ]
            then
                echo ==$fullpathfile not empty==
                frfile $fullpathfile

            else
                echo ==$fullpathfile empty==
            fi
        else
            echo $fullpathfile
            #cat -n $fullpathfile | grep found
        fi

    done
    return
}

basefolder=`dirname $0`
echo "basefolder $basefolder"
frfile $basefolder/$1

对于目录结构如下

# tree emptydir
emptydir
|-- bf       非空目录
|   `-- b.t
|-- def
`-- noted    非空目录
    |-- abc
    `-- ed   空目录
3 directories, 3 files

列出其文件为

# ./listfiles.sh emptydir
basefolder .
./emptydir
======dir======
==./emptydir/bf not empty==
./emptydir/bf
./emptydir/bf/b.t
./emptydir/def
======dir======
==./emptydir/noted not empty==
./emptydir/noted
./emptydir/noted/abc
======dir======
==./emptydir/noted/ed empty==


二、查找目录下包含指定字符串的文件

#!/bin/bash
searchstring=$2
function frfile()
{
    local basefolder=$1
    #echo $basefolder
    for filename in $(ls $basefolder)
    do
        local fullpathfile=$basefolder/$filename
        if [ -d $fullpathfile ]
        then
            #echo ======dir======
            ft=`ls $fullpathfile`
            if [ ! -z "$ft" ]
            then
                #echo ==$fullpathfile not empty==
                frfile $fullpathfile

            #else
                #echo ==$fullpathfile empty==
            fi
        else
            #echo $fullpathfile
            cat -n $fullpathfile | grep "$searchstring"
            if [ $? = 0 ]
            then
                echo $fullpathfile
            fi
        fi
    done
    return
}

basefolder=`dirname $0`
#echo "basefolder $basefolder"
if [ ! -d $basefolder/$1 ]
then
    cat -n $basefolder/$1 | grep "$searchstring"
else
    frfile $basefolder/$1
fi

查找emptydir 目录下 包含字符串“found" 或 ”not found" 的文件并给出字符串在文件中的位置

# ./searchstr.sh emptydir "found"
     1    not found
     2    found
./emptydir/bf/b.t
# ./searchstr.sh emptydir "not found"
     1    not found
./emptydir/bf/b.t

注:b.t文件中共两行即

      not found
      found




  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值