“ 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 获取全部文章目录