一、循环列出目录下所有文件
#!/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