shell实战正则三贱客—grep

发布时间 2023-12-15 14:19:19作者: WeChat2834
三剑客
三剑客特点,及应用场景
命令 特点 场景
grep 过滤 grep过滤速度是最快的
sed 替换,修改文件内容,取行 如果要进行替换/修改文件内容,取出某个范围的内容(从早上10:00到11:00)
awk 取列,统计结算 取列
对比,比较
统计,计算(awk数组)
shell实战正则三贱客—grep
选项 含义
-E ==egrep 支持扩展正则
-A -A5匹配你要的内容显示接下来的5行 (after)
-B -A5匹配你要的内容显示接上面的5行 (before)
-C 匹配你要的内容,并且显示上下5行(context)
-c 统计出现了多少行,类似wc -l
-v 排除,或者取反,按行为单位 |grep -v grep排除自个
-n 显示行号
-i 忽略大小写
-w 精确匹配 ; =='\b \b' =='\< \>' 也可以用这两类方式达到类似效果。
[root@localhost ~]# seq 1 10 |grep -B3 3
1
2
3
[root@localhost ~]# seq 1 10 |grep -C2 3
1
2
3
4
5
[root@localhost ~]# seq 1 10 |grep -C 2 3
1
2
3##上下2行
4
5
[root@localhost ~]# seq 1 10 |grep -c 2 3
grep: 3: 没有那个文件或目录
[root@localhost ~]# seq 1 10 |grep  -c  3
1
[root@localhost ~]# seq 1 10 |grep    3
3
[root@localhost ~]# seq 1 10 |grep    3|wc -l
1
[root@localhost ~]# 
###grep -v 一般用于排除自个,当然还有写特殊写发用其他方式
[root@localhost ~]# ps  -ef|grep crond
root      1221     1  0 11:09 ?        00:00:00 /usr/sbin/crond -n
root      6301  2724  0 14:00 pts/0    00:00:00 grep --color=auto crond
[root@localhost ~]# ps  -ef|grep crond|grep -v grep
root      1221     1  0 11:09 ?        00:00:00 /usr/sbin/crond -n
[root@localhost ~]# ps  -ef|grep [c]rond   #####特殊的其他方式写法也能实现。
root      1221     1  0 11:09 ?        00:00:00 /usr/sbin/crond -n
[root@localhost ~]# 
[root@localhost ~]# echo helloworld  hllke hello heLlow |grep -w hello
helloworld hllke hello heLlow
[root@localhost ~]# echo helloworld  hllke hello heLlow |grep -i hello
helloworld hllke hello heLlow
[root@localhost ~]# echo helloworld  hllke hello heLlow |grep  'hello'
helloworld hllke hello heLlow
[root@localhost ~]# echo helloworld  hllke hello heLlow |grep  '\bhello\b'  ####\b表示边界 ==grep -w
helloworld hllke hello heLlow
[root@localhost ~]# echo helloworld  hllke hello heLlow |grep  '\<hello\>'    ####\<和\>表示边界 ==grep -w
helloworld hllke hello heLlow
[root@localhost ~]# 
helloworld hllke hello heLlow
[root@localhost ~]# echo helloworld  hllke hello heLlow |grep -w hel  
[root@localhost ~]#