•正则就是一串有规律的字符串php
• 掌握好正则对于编写shell脚本有很大帮助shell
• 各类编程语言中都有正则,原理是同样的编程
• 本章将要学习grep/egrep、sed、awkcentos
centos7中grep自带颜色别名,至关于centos6中的 ‘grep --color’:bash
[root@localhost grep]# which grepssh
alias grep='grep --color=auto'编程语言
/usr/bin/grep学习
•grep [-cinvABC] 'word' filenamecentos7
• -c 行数spa
[root@localhost ~]# grep -c 'root' /etc/passwd
2
• -i 不区分大小写
• -n 显示行号
• -v 取反
[root@localhost grep]# grep -v 'nologin' passwd 不显示包含‘nologin’的行
root:x:0:0:root:/root:/bin/bash
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
gavin:x:1000:1000::/home/gavin:/bin/bash
zhang:x:1001:1001::/home/zhang:/bin/bash
user:x:1002:1002::/home/user:/bin/bash
• -r 遍历全部子目录
grep -r 'root' /etc/ 搜索/etc目录下全部文档,并过滤出包含root关键字的行
• -A 后面跟数字,过滤出符合要求的行以及下面n行
• -B 同上,过滤出符合要求的行以及上面n行
• -C 同上,同时过滤出符合要求的行以及上下各n行
• grep -n 'root' /etc/passwd
过滤出包含root的行,并显示行号;
• grep -nv 'nologin' /etc/passwd
过滤出不包含nologin的行,并显示行号
• grep '[0-9]'/etc/inittab
中括号表示其中的任何一个,只要是包含数字的行就会过滤出来
• grep -v '[0-9]'/etc/inittab
过滤出不包含数字的行
• grep -v '^#' /etc/inittab
'^#'表示以#号开头的行,过滤出非#号开头的行;
• grep -v '^#' /etc/inittab|grep -v '^$'
'^$'表示空行,过滤出非#号开头的行,并二次过滤出非空行;
• grep '^[^a-zA-Z]' test.txt
^在外面表示以什么什么开头;^在中括号中表示非什么什么;
过滤出非字母开头的行
• grep -v '[^0-9]' /etc/inittab
匹配包含非数字的行,只排除了全数字的行,其余都会显示;
• grep 'r.o' test.txt
.表示任意的一个字符;'r.o'表示3位字符,以r开头o结尾,中间能够是任意一个字符;
匹配以r开头o结尾,中间能够是任意一个字符的行
• grep 'oo*' test.txt
*表示*号的前一个字符能够有0到n个,重复0次是o,1次是oo,2次是ooo
• grep '.*' test.txt
.*表示任意个任意字符,(全部的都会匹配)
• grep 'o\{2\}' /etc/passwd = grep -E 'o{2}' /etc/passwd = egrep 'o{2}' /etc/passwd
{}花括号在grep中不脱义仅表示搜索包含花括号的,脱义以后表示有2个花括号前面的字符;
• egrep 'o{2}' /etc/passwd
egrep(扩展的grep,包含特殊符号时不用脱义),{}里的数字表示有多少个前面的字符
• egrep 'o+' /etc/passwd
+表示1个或多个+号前面的字符;(+号只对它前面的一个字符起做用,除非括号括起来的总体);
o oo ooo oooo ... 都会被匹配
• egrep 'oo?' /etc/passwd
? 表示0个或1个?号前面的字符
匹配 'o' 'oo'
• egrep 'root|nologin' /etc/passwd
|表示“或”
匹配包含root 或nologin的行
• egrep -v '^#|^$' /etc/ssh/sshd_config
列出非#开头以及非空行
• egrep '(oo){2}' /etc/passwd
()表示括起来的是一个总体;
匹配oooo 的行
把一个目录下,过滤全部*.php文档中含有eval的行:
grep -r --include="*.php" 'eval' /data/