linux使用shell搜索查找文本的几种方法分享_unix linux教程-查字典教程网
linux使用shell搜索查找文本的几种方法分享
linux使用shell搜索查找文本的几种方法分享
发布时间:2016-12-27 来源:查字典编辑
摘要:日志的大小很大,服务器一般也是Linux、HP、AIX等,每次都下载回来就麻烦的要命,在开源中国看到下面内容,很实用。1.使用find和xa...

日志的大小很大,服务器一般也是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

相关阅读
推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
  • 大家都在看
  • 小编推荐
  • 猜你喜欢
  • 最新unix linux学习
    热门unix linux学习
    操作系统子分类