您当前的位置: 首页 > 网络技术  > 服务器教程 浏览
linux使用shell搜索查找文本的几种方法分享
发布时间:2015-12-13    点击率:次    来源:www.sytcke.com    作者:电脑技术学习网

   日志的大小很大,服务器一般也是Linux、HP、AIX等,每次都下载回来就麻烦的要命,在开源中国看到下面内容,很实用。

  1.使用find和xargs命令

  代码如下:

  find dir | xargs grep str # dir是指某个目录

  find file | xargs grep str # file是指某个文件2.

  第2种方法是直接使用grep命令

  代码如下:

  grep str dir/* # dir是指某个目录,但不递归搜索其子目录

  grep -r str dir/* #使用-r选项,递归搜索其子目录

  grep str file #file是指某个文件

  3.第3种方法是综合以上两种

  代码如下:

  #!/bin/bash

  #find_str.sh

  if [ $# -lt "2" ]; then

  echo "Usage: `basename $0` path name [option]"

  exit 1

  fi

  #!-r表示递归处理子目录,-i表示忽略大小写

  path=$1

  name=$2

  shift

  shift

  for option in "$@"

  do

  case $option in

  -r) dir_op="-r"

  ;;

  -i) lu_op="-i"

  ;;

  *) if [ -n "$option" ]; then

  echo "invalid option"

  exit 1

  fi

  ;;

  esac

  done

  grep_str_of_file()

  {

  file=$1

  str=$2

  out=$(grep -n $lu_op "$str" "$file")

  if [ -n "$out" -a "$file" != "$0" ]; then

  echo "$file: $out"

  fi

  }

  find_str()

  {

  if [ -d "$1" ]; then

  for file in $1/*

  do

  if [ "$dir_op" = "-r" -a -d "$file" ]; then

  find_str $file $2

  elif [ -f "$file" ]; then

  grep_str_of_file $file $2

  fi

  done

  elif [ -f "$1" ]; then

  grep_str_of_file $1 $2

  fi

  }

  使用方法

  代码如下:

  $ find_str $path $name

来源 电脑技术网 www.sytcke.com
发表留言
发表留言请先登录!
免责声明:本站发布的信息和评论纯属网民个人行为,并不代表本站立场,如发现有违法信息或侵权行为,请直接与本站管理员联系,我们将在收到您的信息后24小时内作出处理!