加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式

发布时间:2020-12-13 23:10:08 所属栏目:百科 来源:网络整理
导读:grep,egrep,fgrep grep:Global Research Pattern 根据模式,搜索文本,并将符合模式的文本行显示出来。 Pattern :由文本字符和正则表达式的元字符组合成的匹配。 NAME grep,fgrep - print lines matching a pattern SYNOPSIS grep [options] PATTERN [FILE.

grep,egrep,fgrep

grep:Global Research Pattern 根据模式,搜索文本,并将符合模式的文本行显示出来。
Pattern :由文本字符和正则表达式的元字符组合成的匹配。

NAME
grep,fgrep - print lines matching a pattern

SYNOPSIS
grep [options] PATTERN [FILE...]
grep [options] [-e PATTERN | -f FILE] [FILE...]

[root@localhost 3307]# grep 'root' /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin

-i 忽略大小写
--color= 加眼神选项
[root@localhost 3307]# alias grep='grep --color' 可以添加别名

-v 显示没有模式匹配的行
-o 只显示被模式匹配到的字符串

正则表达式:REGular EXPression,REGEXP

* 任意长度的任意字符
?任意单个字符
. 匹配任意单个字符

.* 任意长度的任意字符

? 匹配其前面的字符1次或0次
{m,n} 斜线逃逸字符 匹配其前面的字符至少m次,至多n次
{1,}
{0,3}
位置锚定:

^ 锚定行首,此字符后面的任意内容必须出现首行

[root@localhost 3307]# grep '^root' /etc/passwd
root:x:0:0:root:/root:/bin/bash

$ 锚定行尾,此字符前面的任意内容必须出现行尾

[root@localhost 3307]# grep 'bash$' /etc/passwd
root:x:0:0:root:/root:/bin/bash
cms:x:501:501::/home/cms:/bin/bash
mysql:x:27:27:MySQL Server:/var/lib/mysql:/bin/bash

^$ 匹配空白行
grep -v '^$' /etc/inittab 不显示空白字符

[] 匹配指定范围内的任意单个字符

[^] 匹配指定满园外的任意单个字符

字符集合
[:digit:],[:lower:],[:upper:],[:punct:],[:space:]

[root@localhost 3307]# grep '[[:digit:]]$' /etc/inittab
# 5 - X11
l0:0:wait:/etc/rc.d/rc 0
l1:1:wait:/etc/rc.d/rc 1
l2:2:wait:/etc/rc.d/rc 2
l3:3:wait:/etc/rc.d/rc 3
l4:4:wait:/etc/rc.d/rc 4
l5:5:wait:/etc/rc.d/rc 5
l6:6:wait:/etc/rc.d/rc 6
1:2345:respawn:/sbin/mingetty tty1
2:2345:respawn:/sbin/mingetty tty2
3:2345:respawn:/sbin/mingetty tty3
4:2345:respawn:/sbin/mingetty tty4
5:2345:respawn:/sbin/mingetty tty5
6:2345:respawn:/sbin/mingetty tty6
# Run xdm in runlevel 5

&;或 broot 锚定词首,其后面的任意字符必须作为单词的首部出现 &;root 以root为词首的 broot
&; 或 rootb 锚定词尾,其前面的任意字符必须作为单词的尾部出现 root&; 以root为词尾的 rootb
&;root&;

分组
()
(ab)*
1,2 引用括号的内的次数
grep '^1([0-9]):1.*1$' /etc/inittab
==================================================================================================
扩展正则表达式
Baseic REGEXP 基本正则表达式
Extended REGEXP 扩展正则表达式 默认工作在贪婪模式下
字符匹配
.
[]
[^]
次数匹配
*

+ 至少一次,匹配其前面的字符至少1次
{m,n} 不需要使用线转意

位置锚定字符都一样

分组:
() 不需要加反斜线
1,2,3 ....

或者

a| b 代表 or

grep --color -E 'C|cat' rg 代表匹配大写小写Cc

fgrep : fast 快速的,不支持正则表达式

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读