写一个通用的搜索字符所在位置的工具

  这些天也没学到什么新东西,因为前几天把硬盘重新分区了,又将整个电脑的状态恢复了原样,整个过程移动了70多G的数据,却没有使用到移动硬盘,真的感谢Linux的伟大。

  因为在分区之前Linux社区里的一个朋友问了这个主题的问题,我当时没有认真思考,只是给了一条可以当做答案的命令。后来自己要用到了,也想起来了这个命令。可是仔细一想,找出一个变量或者字符串的所在文件却是是个很常见的问题,所以就有了一个做出通用工具的想法。打算用一个简单的Shell脚本来实现,如下所示:

#!/bin/sh

# Script Name is search .

# This is a script that can search for a string from many files
# to find out the location of the string .

##### 使用说明 #####
usage ()
{
    cat <<EOF
Usage: `basename $0` <string> <path>

Example: search LANG /etc

EOF
    exit 0
}

#### 分析命令参数 ####
parse_cmdline()
{
    if [ $# -gt 1 ]
    then
        if [[ -f $2 || -d $2 ]];then
            str="$1"
            path="$2"
        fi
    else
        usage
    fi
}

#### 搜索核心代码 ####
search ()
{
    for file in $(find $path)
    do
        grep -n $str $file 2>/dev/null
        ret=$?
        if [ $ret -eq 0 ]
        then
            echo "
"$str" may be in "$file" !
"
        fi
    done
    exit 0
}

# Start Search

parse_cmdline $@
search

# End Of File

  以上脚本只是个人心得,不算什么大作,只是比较实用一些,在此分享出来。

参考:

  http://www.cnblogs.com/276815076/archive/2011/10/30/2229286.html

  http://www.cnblogs.com/chengmo/archive/2010/10/01/1839942.html

原文地址:https://www.cnblogs.com/vnix/p/search-shell.html