[Linux]grep和find配套查找字符串技巧

find中使用正则表达式的语法是:

find dir -regextype type -regex "pattern"

其中:
dir:查找文件的起始目录
-regextype "type":选择使用正则表达式的类型,如下:
type: posix-awk, posix-basic, posix-egrep和posix-extended四种。常用的是后两种。
pattern: find中要想使用正规正则表达式,需要用选项 -regex "pattern"。而pattern就用相应类型风格的正则表达式替换即可。
注意:find的常用选项-name是不支持正则表达式的,充其量只能说-name选项支持通配符 * ? []。
[abc]:表示可以匹配abc中的任意一个
[^abc]:表示不匹配abc,^:表示取反
find . -regextype posix-extended -regex ".*\.[^oa]\>"
表示匹配不以.a或者.o结尾的文件名

1,从目录或者文件中搜索文本字符串

grep -rniw "字符串" "输入目录或文件路径"

选项:
-e, --regexp=PATTERN use PATTERN for matching
-r, --recursive like --directories=recurse
-n, --line-number print line number with output lines
-w, --word-regexp force PATTERN to match only whole words
-i, --ignore-case ignore case distinctions

2,搜索不以".o"结尾的文件名

find . -type f ! -name "*.o"
find . -regextype posix-extended -regex ".*\.[^o]\>"

3,搜索不以".o"或".a"结尾的文件名

find . -type f ! -name "*.o" ! -name "*.a "
find . -regextype posix-extended -regex ".*\.[^oa]\>"
grep -rniw --color=auto "xxx" $(find . -regextype posix-extended -regex ".*\.[^oa]\>")

4,写成脚本的形式+配置别名

(1)新建cgrep.sh脚本文件

#!/bin/sh

dir=`pwd`
if [ $# -eq 2 ]; then
        dir=$2
        for path in `ls ${dir}`
        do    
                real_path="${dir}/${path}"
                if [ -d "${real_path}" ];then
                        cd "${real_path}" > /dev/null
                        for file_name in $(find . -regextype posix-extended -regex ".*\.[^oa]\>")
                        do
                                if [ -f ${file_name} ];then
                                        grep -rniwH --color=auto $1 ${file_name}
                                fi
                        done
                        #grep -rniw --color=auto $1 $(find . -regextype posix-extended -regex ".*\.[^oa]\>")
                        cd -  > /dev/null
                else
                    grep -rniw --color=auto $1 "${real_path}"
                fi
        done
else
        grep -rniw --color=auto $1 "${dir}"
fi

(2)设置别名cgrep

sudo vim ~/.bashrc
alisa cgrep=路径/cgrep.sh
source ~/.bashrc

(3)在路径下搜索字符串"xxx"

$ cgrep "xxx" "搜索路径"

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值