linux sh文件查找内容,linux使用shell搜索查找文本的几种方法分享

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值