随笔-149  评论-223  文章-30  trackbacks-0
方法1:使用find和xargs命令
     find dir | xargs grep str,dir是指某个目录
     find file | xargs grep str,file是指某个文件
   注意:这种方法,会递归搜索子目录

方法2:直接使用grep命令
     grep str dir/*,dir是指某个目录,但不递归搜索其子目录
     grep -r str dir/*,使用-r选项,递归搜索其子目录
     grep str file,file是指某个文件

方法3:综合以上两种,写一个shell脚本,代码如下 
 1#! /bin/bash
 2# findstr.sh   
 3
 4if [ $# -lt "2" ]; then
 5   echo "Usage: `basename $0` path name [option]"
 6   exit 1
 7fi   
 8
 9path=$1
10name=$2  
11shift 
12shift   
13
14for option in "$@"
15do
16   case $option in
17   -r) dir_op="-r"
18   ;;
19   -i) lu_op="-i"
20   ;;
21   *if [ -"$option" ]; then
22         echo "invalid option"
23         exit 1
24       fi
25   ;;
26  esac
27done    
28
29grep_str_of_file()
30{
31     file=$1
32     str=$2
33     out=$(grep -n $lu_op "$str" "$file")
34     if [ -"$out" -"$file" != "$0" ]; then
35        echo "$file: $out"
36     fi
37}    
38
39find_str()
40{
41  if [ -"$1" ]; then
42     for file in $1/*
43      do
44        if [ "$dir_op" = "-r" --"$file" ]; then
45            find_str $file $2
46        elif [ -"$file" ]; then
47           grep_str_of_file $file $2
48        fi
49     done
50 elif [ -"$1" ]; then
51   grep_str_of_file $1 $2    
52 fi
53}  
54
55find_str $path $name
  这样一来,不管$1参数是目录还是文件,都能处理,使用示例如下:
    findstr /usr/include main          不递归搜索子目录,大小写敏感
    findstr /usr/include main -i       不递归搜索子目录,忽略大小写
    findstr /usr/include main -r       递归搜索子目录,大小写敏感
    findstr /usr/include main -r  -i   递归搜索子目录,忽略大小写
 
    findstr main.cpp main              在文件中搜索,大小写敏感
    findstr main.cpp main -i           在文件中搜索,忽略大小写 

  上面所述的示例中,str不限于特定的文本,可以是带正则表达式的匹配模式。而第3种方法,也可以用sed替换grep来显示文本行,在此基础上能作更多的处理,比如格式化显示、统计匹配的文本个数、搜索策略等,在此就不详究了。
posted on 2011-08-20 19:46 春秋十二月 阅读(2414) 评论(0)  编辑 收藏 引用 所属分类: System

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理