「Linux」grep和find配套查找字符串技巧

「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" "搜索路径"

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章