shell grep文本搜索

grep语法:

grep [option] "string_to_find" filename

选项与参数:

(1)-i:忽略搜索字符串的大小写

(2)-v:取反,即输出不匹配的那些文本行

(3)-n:输出行号

(4)-l:输出能够匹配模式的文件名,相反的选项为-L

(5)-q:静默输出

(6)-w:精准匹配

根据实际需求进行选择即可

string_to_find为需要匹配的模式,可以填写字符串或者正则表达式

filename为需要查找的文件的名称

现有文件test_001.txt,文件内容如下:

yello
hello,hello
hello,hello
hello,hello
hello,hello
hello,hello
hello world

1.统计文件中能够匹配的行数
grep -c "hello" test_001.txt

结果:6

2.统计文件中匹配的数量
grep -o "hello" test_001.txt | wc -l

结果:11

3.递归搜索
-r:grep的参数filename为目录时可以加上本选项表示递归搜索
列如:文件test_001.txt的上一层目录为:sj_add
grep -r "hello" sj_add

结果:

sj_add/test_001.txt:hello,hello
sj_add/test_001.txt:hello,hello
sj_add/test_001.txt:hello,hello
sj_add/test_001.txt:hello,hello
sj_add/test_001.txt:hello,hello
sj_add/test_001.txt:hello world

4.匹配多个正则表达式:-e:该选项加上正则表达式就是一个需要匹配的模式
找出匹配hello或者world的行
grep -e "hello" -e "world" test_001.txt

结果:

hello,hello
hello,hello
hello,hello
hello,hello
hello,hello
hello world

5.指定/排除文件
--include:指定需要搜索的文件
--exclude:排除需要搜索的文件
--exclude-dir:排除需要搜索的目录
例子:
(1)搜索sj_add目录中.txt和.cpp文件中的含有yello的行:
grep -r "yello" ./sj_add --include *.{txt,cpp}
(2)搜索sj_add目录中含有yello的行,但不搜索readme文件:
grep -r "yello" ./sj_add --exclude "readme"
(3)搜索sj_add目录中含有yello的行,但不搜索.git文件夹:
grep -r "yello" ./sj_add --exclude-dir ".git"

原文地址:https://www.cnblogs.com/Arabi/p/11572660.html