最近几天在看前几届师兄写的一个项目,经常需要查找变量和函数的定义,一直用命令find ./ -type f -print|xargs grep 查找内容,感觉很不灵活,正好打算学习shell,就自己写了个shell脚本,在此作下记录。
此shell的功能是查找某个目录下的所有文件中包含某个字符串的行,并以“文件名-行号”显示:这个项目目录下只有一层子目录,所以这个shell中只考虑了两层目录,还有需要对文件权限、类型做进一步处理,输出格式也需要修改下。
#!/bin/bash
if [ $# -ge 1 ]
then
sCont=$1
else
echo "please type in the word to be searched"
exit 1
fi
path="."
if [ $# -ge 2 ]
then
path=$2
fi
filelist=`ls $path`
#echo $filelist
for file in $filelist
do
#echo $file
if test -f $file
then
#echo "ordinary file $file"
#res=''
if res=`grep -n $sCont $file`
then
echo "--------------has find in $file-------------"
for item in $res
do
echo $item
done
fi
elif test -d $file
then
#echo "directory $file"
sub=`ls $file` #search depth is two level,if want more ,need recursive function
for subfile in $sub
do
if test -f ./$file/$subfile
then
#res=''
if res=`grep -n $sCont ./$file/$subfile`
then
echo "--------------has find in ./$file/$subfile-------------"
for item in $res
do
echo $item
done
fi
fi
done
fi
done