shell脚本:打印指定目录下所以.c文件中指定两个字符串出现的行号

打印指定目录下所以.c文件中指定两个字符串出现的行号

#!/bin/bash 
#find files contains a keyword 
#write by qiuping.wang 
#2018.08.14 
echo -e "\nThis is a script to find all the files in a specified path contains a keyword!" 
echo -e "\nPlease input two keyword:" 
read key1 
read key2 
if [ "$key1" == "" ] || [ "$key2" == "" ]; then #判断变量是否为空 if[ ]
    echo -e "keyword can not be null!\n" 
    exit 0 
else
keyword1=$key1
keyword2=$key2 
echo -e "\nPlease input your specified path:" 
read dir 
#判断该路径是否存在,并且是目录,不存在输出提示 
test ! -d $dir && echo -e "The $dir is not exist in your system.\n\n" && exit 0  #替换test命令。使用if语句
 
echo -e "\n---------------You find files are:---------------\n" 
 
#keyword=JAVA_OPTS 
#dir=/jboss/jboss-eap-4.3/jboss-as/ 
 
#统计文件个数 
file_count=0 
#递归查看所有目录,即最深路径,不显示空行 
file_list=`ls -R $dir 2> /dev/null | grep -v '^$'` 
for file_name in $file_list 
do 
    #临时文件变量temp,将ls -R即file_list中的文件名中所有匹配:后接一个或多个任意字符(.代表任意字符,*代表0个或多个$代表行尾结束符)全局替换为无 
    #简单的说,就是把file_name变量中的匹配:的行,将:后内容替换为空 
    temp=`echo $file_name | sed 's/:.*$//g'` 
    #如果临时文件变量temp是一个目录,而非文件,就将该目录赋值给cur_dir变量 
    if [ "$file_name" != "$temp" ]; then 
        cur_dir=$temp 
        #echo "-"$cur_dir #临时显示,调试用 
    else 
        #用file命令查看文件真身是否为ASCII text类型 
        file_type=`file $cur_dir/$file_name | grep "text"` 
        if [ "$file_type" != "" ]; then 
            temp1=`grep $keyword1 $cur_dir/$file_name 2> /dev/null` 
	    temp2=`grep $keyword2 $cur_dir/$file_name 2> /dev/null` 
            #echo "--"$cur_dir/$file_name #临时显示,调试用 
            if [ "$temp1" != "" ] && [ "$temp2" != "" ]; then 
				echo  $cur_dir/$file_name  >> log
				echo -n "keyword1 :" $keyword1 >> log && echo -n " " >> log
				echo -n "keyword1 count :" >>log
				cat -n $cur_dir/$file_name|grep $keyword1 |awk '{print $1}' | wc -l >> log
				echo  -n "keyword2 :" $keyword2 >> log && echo -n " " >> log
				echo -n "keyword2 count :" >>log
				cat -n $cur_dir/$file_name|grep $keyword2 |awk '{print $1}' | wc -l >> log
                #文件个数加1 
                let file_count++ 
            fi 
        fi 
    fi 
done 
 
echo -e "\n-------------------------------------------------" 
echo -e "\n\nFiles Total: $file_count" 
echo -e "\nFind Finished!\n" 
fi 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值