正则表达式:
由一类字符书写的模式,其中有些字符不表示字符的字面意义,而是表示控制或通配的功能
Linux grep命令:
简介
grep (globl search regular expression(RE) and print out the line)是一种强大的文本搜索工具,他能使用正则表达式搜索文本,并把匹配的行打印出来
使用格式:
grep [OPTION]... ‘PATTERN‘ FILE...
grep常用选项:
-v: 反向选取
-o: 仅显示匹配到内容
-i: 忽略字符大小写
-E: 使用扩展正则表达式
-A #:打印出紧随匹配行的下#行
-B #:打印出紧随匹配行的上#行
-C #:打印出紧随匹配行的上#行和下#行
[[email protected] ~]# grep ‘root‘ /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
[[email protected] ~]# grep -v ‘root‘ /etc/passwd
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
... ...
[[email protected] ~]# grep -o ‘root‘ /etc/passwd
root
root
root
root
[[email protected] ~]# grep -i ‘f‘ /proc/meminfo
MemFree: 373136 kB
Buffers: 70284 kB
Active(file): 88996 kB
Inactive(file): 426536 kB
SwapFree: 2097144 kB
NFS_Unstable: 0 kB
HugePages_Free: 0
[[email protected] ~]# grep -A2 ‘root‘ /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
--
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
gopher:x:13:30:gopher:/var/gopher:/sbin/nologin
[[email protected] ~]# grep -C2 ‘uucp‘ /etc/passwd
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
[[email protected] ~]# grep ‘o\{2\}‘ /etc/passwd
root:x:0:0:root:/root:/bin/bash
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
[[email protected] ~]# egrep ‘o{2}‘ /etc/passwd
root:x:0:0:root:/root:/bin/bash
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
[[email protected] ~]# grep -E ‘o{2}‘ /etc/passwd
root:x:0:0:root:/root:/bin/bash
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin