当前位置:网站首页>Shell 编程正则表达式及元字符

Shell 编程正则表达式及元字符

2022-06-12 19:03:00 benziwu

目录

正则表达式

^ :首位定位符

$ :行尾定位符

. :匹配任意单个字符

* :匹配前导符0到多次;只能在后面使用

.* :任意多个字符

[ ] : 匹配指定范围内的字符

[^] 匹配不在指定组内的字符

\ :用来转义元字符(''  ""   \),脱意符

\<  词首定位符

\> 词尾定位符

()   匹配稍后使用的字符的标签

x\{m\}  字符x重复出现m次

x\{m,n\} 字符x重复出现m到n次

扩展正则表达式元字符

+  匹配1~n个前导字符

? 匹配0~1个前导字符

a|b  匹配a或者b


正则表达式

元字符

定义:元字符是这样一类字符,他们表达的是不同字面本身的含义

^ :首位定位符

[[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 "^root" /etc/passwd
root:x:0:0:root:/root:/bin/bash

$ :行尾定位符

. :匹配任意单个字符

[[email protected] ~]# cat 1.txt
abc
adc
bac
[[email protected] ~]# grep abc 1.txt
abc
[[email protected] ~]# grep a.c 1.txt
abc
adc
[[email protected] ~]# grep ..c 1.txt
abc
adc
bac
[[email protected] ~]# grep .bc 1.txt
abc
[[email protected] ~]# grep ab. 1.txt
abc

* :匹配前导符0到多次;只能在后面使用

[[email protected] ~]# grep "abc*" 1.txt
abc
abcdffe
abcddfgh

.* :任意多个字符

[[email protected] ~]# grep "ab.*" 1.txt
abc
abcdffe
abcddfgh
您在 /var/spool/mail/root 中有新邮件
[[email protected] ~]# grep "ab.*h" 1.txt
abcddfgh
[[email protected] ~]# grep "ab.*g" 1.txt
abcddfgh

[ ] : 匹配指定范围内的字符

[[email protected] ~]# grep [iL]ove 1.txt
Love

[[email protected] ~]# cat 1.txt
abc
adc
bac
abcdffe
abcddfgh
ggg

love
LOve
Love
i love
i love you
hhhh

[[email protected] ~]# grep [lL]ove 1.txt
love
Love
i love
i love you

[^] 匹配不在指定组内的字符

类似!在“[]” ^  不匹配

  

 \ :用来转义元字符(''  ""   \),脱意符

[[email protected] ~]# grep "l." 1.txt
love
i love
i love you
l.ve
[[email protected] ~]# grep "l\." 1.txt
l.ve

\<  词首定位符

\> 词尾定位符

()   匹配稍后使用的字符的标签

 

 x\{m\}  字符x重复出现m次

[[email protected] ~]# grep o 1.txt
#love
Love
i love
i love you

[[email protected] ~]# grep "h\{3\}" 1.txt
hhhh
abcdefhhhgggff

 x\{m,n\} 字符x重复出现m到n次

[[email protected] ~]# grep "h\{3,5\}" 1.txt
hhhh
abcdefhhhgggff

扩展正则表达式元字符

+  匹配1~n个前导字符

[[email protected] ~]# egrep lo+ve   1.txt 
#love
i love
i love you

? 匹配0~1个前导字符

lo?ve:?  前面的o有还是没有,都行!

[[email protected] ~]# egrep lo?ve   1.txt 
#love
i love
i love you
lve
love

a|b  匹配a或者b

 () 组字符

 

 

 

原网站

版权声明
本文为[benziwu]所创,转载请带上原文链接,感谢
https://blog.csdn.net/benziwu/article/details/125245087