Linux三剑客老三 grep

本文深入讲解Linux下grep命令的高级用法,包括递归查找、大小写敏感、行号显示及正则表达式匹配等实用技巧,帮助读者快速定位和解决日志问题。
“ linux三剑客,最常用的linux命令之grep——编程三分钟”

grep 参数解释

grep擅长查找功能

在这里为了节省篇幅,我就不一一解释了,只介绍一些非常常用的组合。

递归查找所有匹配的文件内容

$ grep -rl love *
dir/file3.txt
file.txt
file2.txt

复制代码

忽略大小写递归查找并带行号输出

$ grep -inr "It doesn’T" *
dir/file3.txt:38:It doesn’t matter where 
file.txt:38:It doesn’t matter where 
file2.txt:38:It doesn’t matter where

复制代码

忽略大小写显示行号,显示匹配内容和前后2行

一般用于定位日志问题,-A 2 -B 2 也可以替换成-C 2
$ grep -in "It doesn’T" file.txt -A 2 -B 2
file.txt-36-the way that ypu change my world
file.txt-37-when I’m with you
file.txt:38:It doesn’t matter where we're from and where
file.txt-39-as long as your with me all the way
file.txt-40-And the nights are long and lonely and

复制代码

查找匹配的进程名,忽略带grep的内容

$ ps -ef | grep -i wei
  501 1807 1 0 25 519 ?? 5:29.55 /usr/bin/Weiyun -psn_0_176171
  501 92256 1851 0 10:32 grep --color=auto 
$ ps -ef | grep -i wei | grep -v grep
  501 1807 1 0 25 519 ?? 5:29.55 /usr/bin/Weiyun -psn_0_176171

复制代码

或逻辑查找

$ grep -E "love|change" file.txt
I love you
I love you
the way that you change my world
Love may come and love may go复制代码

正则表达式测试

最骚的就数这个了,不用再下载一堆东西或者打开某个网页在测试正则表达式了,比如校验json、校验邮箱。一个grep就搞定,是不是很方便呢?
echo coding3min@foxmail.com | grep -p "^[A-Za-z0-9\u4e00-\u9fa5]\+\@[a-zA-Z0-9_-]\+\(\.[a-zA-Z0-9_-]\+\)"
coding3min@foxmail.com复制代码
关注公众号回复 m 获取全部文章目录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值