Linux中查寻包含特定字符串的所有文件

Linux中查找包含特定字符串的所有文件

1.findtxt.sh

#!/bin/bash 

 

echo -e "\nThis script finds files in a specific dir with a keyword.\nOK,Please input a keyword:"

 

read keyword

if [ "$keyword" = "" ]; then 

    echo  "keyword can not be null!\n"

    exit 0

fi 

      

echo "\nPlease input the dir path:"

read dirPath

while [ "$dirPath" = "" ]

do

  echo  "The dir can't be null,pls input it again"

  read  dirPath

done

 

if [ ! -d "$dirPath" ]; then

  echo "The $dirPath is not exist!\n\n"

  exit 0

fi

      

echo  "\n--------------- Find these files ---------------\n"

 

fileCount=0

files=`ls -R $dirPath 2> /dev/null | grep -v '^$'`

for fileName in $files

do  

    temp=`echo $fileName | sed 's/:.*$//g'`

    if [ "$fileName" != "$temp" ]; then 

        currentDir=$temp

    else 

        fileType=`file $currentDir/$fileName | grep "text"`

        if [ "$fileType" != "" ]; then 

            temp=`grep $keyword $currentDir/$fileName 2> /dev/null`

            if [ "$temp" != "" ]; then 

                echo $currentDir/$fileName

                fileCount=`expr $fileCount + 1`

            fi 

        fi 

    fi 

done 

if [ $fileCount -gt 0 ];then

  echo "\n\nFiles Total: $fileCount"

  echo "\nFind Finished!\n"

else

  echo "No files found!"

fi

 

2.将以上findtxt.sh放在任意目录下,如:/home/findtxt.sh

 

3.切换到当前用户目录下:cd ~

编辑.bashrc文件

在文件的最末尾添加:

#alias for the find special content in the type files of text

alias findtxt='sh /home/findtxt.sh'

 

4.重新登录后生效。

 

5. tom@tom-VirtualBox:~$ findtxt

This script finds files in a specific dir with a keyword.

OK,Please input a keyword: