正则表达式
正则表达式是由一些具有特殊含义的字符组成的字符串,多用于查找、替换符合规则的字符串。在表单验证、Url映射等处都会经常用到。
说简单点就是王者荣耀里的***。
作用
通过文件中的那人进行过了赛选,然后对文件的内容进行处理。经常用于基于正则写脚本来处理日志文件。
构成
一堆特殊符号和字母构成 ,一般称为元字符。
正则表达式的种类
-
基本正则表达式
-
扩展正则表达式
正则表达式的使用
通常都会结合三个命令使用,俗称三剑客。
-
grep
-
sed
-
awk
grep 命令
选项:
例子:
1 [root@shell ttt]# cat grep_t.txt 2 a root if is and 3 -++ -i or dir 4 root bing ping pr 5 dors jlkf klj 6 are root you root am your 7 8 # 取反,也就是过滤掉有root的行输入没有root的行 9 [root@shell ttt]# grep -v root grep_t.txt 10 -++ -i or dir 11 dors jlkf klj 12 13 #直显示 root 14 [root@shell ttt]# grep -o root grep_t.txt 15 root 16 root 17 root 18 root 19 20 # 统计个数 21 [root@shell ttt]# grep -o root grep_t.txt | wc -l 22 4 23 [root@shell ttt]# grep --color root grep_t.txt 24 a root if is and 25 root bing ping pr 26 are root you root am your
通配符和正则的区别
正则中的云字符
匹配元字符
实例:
1 [root@shell ttt]# cat grep_t.txt 2 a root 3 if is and 3 -++ -i or 4 dir 4 root bing 5 ping pr 5 dors jlkf 33 klj 6 are root 71 you root 7 am your 7 8 # 匹配前面一个字符后面是一个a的行 9 [root@shell ttt]# grep ".a" grep_t.txt 10 a root 3 if is and 11 are root 71 you root 7 am your 12 # 匹配前后有字符,中间有a的行号 13 [root@shell ttt]# grep ".a." grep_t.txt 14 a root 3 if is and 15 are root 71 you root 7 am your 16 17 # 匹配 0-9 范围内的任意字符 18 [root@shell ttt]# grep [1-9] grep_t.txt 19 a root 3 if is and 20 -++ -i or 4 dir 21 root bing 5 ping pr 22 dors jlkf 33 klj 23 are root 71 you root 7 am your 24 # 匹配所有数字范围内的任意字符 25 [root@shell ttt]# grep [[:digit:]] grep_t.txt 26 a root 3 if is and 27 -++ -i or 4 dir 28 root bing 5 ping pr 29 dors jlkf 33 klj 30 are root 71 you root 7 am your 31 32 # 匹配指定单词外的任意字符 33 [root@shell ttt]# grep "[^a]" grep_t.txt 34 a root 3 if is and 35 -++ -i or 4 dir 36 root bing 5 ping pr 37 dors jlkf 33 klj 38 are root 71 you root 7 am your 39 或 40 # 只匹配开头行 41 grep "^[^a]" grep_t.txt or grep -v "[^a]" grep_t.txt
显示匹配到行前后若干行
1 -A n 显示匹配行后n行 2 -B n 显示匹配行前n行 3 -C n 显示匹配行前后的各n行
次数匹配
* 表示其前面的字符出现任意此次数的情况,(0,1,n)次数 ==> grep "a*b" 文件名 #匹配a后面b出现多次 .* 表示任意长度的任意字符 ==> grep "a.*b" 文件名 #过滤出包含字母a和b行,要求a在前,b在后 ? 表示其前面最多出现一次的情况 ==> grep "a?b" 文件名 #过滤出b只能出现一次 \{m,n\} 表示其前面的字符出现最少m次,最多n次 ==> grep "a\{2,5\}b" 文件名 #过滤出b前面2-5个a
位置锚定
^ 锚定行首 ==> grep "^root" 文件名 #过滤出以root开头的行 $ 锚定行尾 ==> grep "root$" 文件名 #过滤出以root结尾的行 ^$ 表示空白行 ==> grep "^$" 文件名 #过滤出空白行 \<或\b 字符必须作为单词首部出现 ==> grep "\<root" 文件名 #首单词为root的行 \>或\b 字符必须作为单词尾部出现 ==> grep "root\>" 文件名 #尾单词尾root的行
分组
\( \) 将一个内容当做一个整体看待 \1 表示引用前面第一个分组 ==> grep "\([[:digit:]]\).*\1" 文件名 #过滤出两个相同数字的行 \2 表示引用前面第二个分组
扩展正则表达式
扩展表达式:
支持字符匹配(. 、[] 、[^])、次数匹配(* 、?、{m,n})。
补充
在基本表达式中,? {} () 需要在前面使用 \ 进行转义
在扩展正则表达式中不需要的
扩展 或
1 # 过滤出bing 跟 Bing 2 [root@shell ttt]# grep -E "(b|B)ing" grep_t.txt 3 root bing 5 ping pr 4 Bing bing 5 # 直接过滤掉大小写 bing 6 [root@shell ttt]# grep -i bing grep_t.txt 7 root bing 5 ping pr 8 Bing bing
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。