三剑客之grep

根据内容过滤文本信息
grep
[root@rstx-201 ~]# grep root /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin

加上通配符^  以root开头
grep ^root /etc/passwd
root:x:0:0:root:/root:/bin/bash

加上通配符$  以bash结尾
grep bash$ /etc/passwd
root:x:0:0:root:/root:/bin/bash
postgres:x:26:26:PostgreSQL Server:/var/lib/pgsql:/bin/bash
yangtao:x:1001:1001::/home/yangtao:/bin/bash
grep -n 显示过滤的行号
[root@rstx-53 odoo-backup]# grep -n  root /etc/services 
1829:rootd           1094/tcp                # ROOTD
1830:rootd           1094/udp                # ROOTD
grep -n -A 3 匹配到的结果向下展示三行
[root@rstx-53 odoo-backup]# grep -n -A3  root /etc/services 
1829:rootd           1094/tcp                # ROOTD
1830:rootd           1094/udp                # ROOTD
1831-nicelink        1095/tcp                # NICELink
1832-nicelink        1095/udp                # NICELink
1833-cnrprotocol     1096/tcp                # Common Name Resolution Protocol
grep -n -B 3 匹配到的结果向上展示三行
[root@rstx-53 odoo-backup]# grep -n -B3  root /etc/services 
1826-obrpd           1092/udp                # Open Business Reporting Protocol
1827-proofd          1093/tcp                # PROOFD
1828-proofd          1093/udp                # PROOFD
1829:rootd           1094/tcp                # ROOTD
1830:rootd           1094/udp                # ROOTD
grep -n -C 3 匹配到的结果向上展示三行向下展示三行
[root@rstx-53 odoo-backup]# grep -n -C3  root /etc/services 
1826-obrpd           1092/udp                # Open Business Reporting Protocol
1827-proofd          1093/tcp                # PROOFD
1828-proofd          1093/udp                # PROOFD
1829:rootd           1094/tcp                # ROOTD
1830:rootd           1094/udp                # ROOTD
1831-nicelink        1095/tcp                # NICELink
1832-nicelink        1095/udp                # NICELink
1833-cnrprotocol     1096/tcp                # Common Name Resolution Protocol
grep -i 过滤的字符不区分大小写
[root@rstx-53 ~]# cat test.txt 
root
ROOT
[root@rstx-53 ~]# grep -n root test.txt 
1:root
[root@rstx-53 ~]# grep -n -i root test.txt 
1:root
2:ROOT
grep -v 取反
[root@rstx-53 ~]# cat test.txt 
root
ROOT
[root@rstx-53 ~]# grep  root test.txt 
root
[root@rstx-53 ~]# grep -v  root test.txt 
ROOT
grep -E 过滤多个字符串
[root@rstx-53 ~]# grep -Ei   "root|ROOT"  test.txt 
root
ROOT
[root@rstx-53 ~]# egrep   "root|ROOT"  test.txt 
root
ROOT
grep -w 设定边界过滤
[root@rongbiz002 26]# ifconfig eth0|grep -w inet
        inet 192.168.0.35  netmask 255.255.0.0  broadcast 192.168.255.255
grep -o 显示匹配过程
[root@RainGod ~]# cat test.txt 
11

22
[root@RainGod ~]# grep "." test.txt -o 
1
1
2
2
posted @ 2021-05-31 17:49  老夫聊发少年狂88  阅读(63)  评论(0编辑  收藏  举报