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”

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值