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

来源:互联网 发布:淘宝微淘的好处 编辑:程序博客网 时间:2024/06/02 10:18

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

#!/bin/bashfunction 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 emptydiremptydir|-- bf       非空目录|   `-- b.t|-- def`-- noted    非空目录    |-- abc    `-- ed   空目录3 directories, 3 files

列出其文件为

# ./listfiles.sh emptydirbasefolder ../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/bashsearchstring=$2function 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/$1fi

查找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 0
原创粉丝点击