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 获取所有文章目录
相关文章
相关标签/搜索