查找目录下文件中是否包含某字符串的shell脚本

最近几天在看前几届师兄写的一个项目,经常需要查找变量和函数的定义,一直用命令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


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值