一:概述

  • 正则表达式使用单个字符串来描述、匹配一系列符合某个语法规则的字符串。
  • 通常被用来检索、替换那些符合某个模式的文本。
  • 在 Linux 中,grep, sed,awk 等文本处理工具都支持通过正则表达式进行模式匹配。

二:常规匹配

一串不包含特殊字符的正则表达式匹配自身;

1
2
3
# 匹配所有包含 ghost 的行
[root@hadoop100 ~]# cat /etc/passwd | grep ghost
ghost:x:1000:1000:ghost:/home/ghost:/bin/bash

三:常用特殊字符

(1)特殊字符:^

  • ^ 匹配一行的开头
1
2
3
4
5
# 匹配所有以a开头的行
[root@hadoop100 ~]# cat /etc/passwd | grep ^a
adm:x:3:4:adm:/var/adm:/sbin/nologin
abrt:x:173:173::/etc/abrt:/sbin/nologin
avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin

(2)特殊字符:$

  • $ 匹配一行的结束
1
2
3
4
# 匹配以 bash 结尾的行
[root@hadoop100 ~]# cat /etc/passwd | grep bash$
root:x:0:0:root:/root:/bin/bash
ghost:x:1000:1000:ghost:/home/ghost:/bin/bash
  • ^$ 匹配什么?
1
2
3
4
5
6
7
8
# 匹配出 initial-setup-ks.cfg 中的空行,并显示行号
[root@hadoop100 ~]# cat initial-setup-ks.cfg | grep -n ^$
20:
25:
39:
60:
62:
65:

(3)特殊字符:.

  • . 匹配一个任意的字符
1
2
3
4
[root@hadoop100 ~]# cat /etc/passwd | grep b..h
root:x:0:0:root:/root:/bin/bash
chrony:x:992:987::/var/lib/chrony:/sbin/nologin
ghost:x:1000:1000:ghost:/home/ghost:/bin/bash

(4)特殊字符:*

  • * 不单独使用,他和上一个字符连用,表示匹配上一个字符 0 次或多次
  • 匹配到:rt、rot、root、rooot…的所有行
1
2
3
4
5
[root@hadoop100 ~]# cat /etc/passwd | grep ro*t
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
abrt:x:173:173::/etc/abrt:/sbin/nologin
rtkit:x:172:172:RealtimeKit:/proc:/sbin/nologin
  • .* 匹配什么?
1
2
3
4
5
6
7
8
9
# g开头t结尾,中间是任意字符出现任意次
[root@hadoop100 ~]# cat /etc/passwd | grep g.*t
systemd-network:x:192:192:systemd Network Management:/:/sbin/nologin
libstoragemgmt:x:998:995:daemon account for libstoragemgmt:/var/run/lsm:/sbin/nologin
gluster:x:995:992:GlusterFS daemons:/run/gluster:/sbin/nologin
tss:x:59:59:Account used by the trousers package to sandbox the tcsd daemon:/dev/null:/sbin/nologin
gnome-initial-setup:x:988:982::/run/gnome-initial-setup/:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
ghost:x:1000:1000:ghost:/home/ghost:/bin/bash

(5)字符区间(中括号):[ ]

  • 表示匹配某个范围内的一个字符,例如 [6,8]——匹配 6 或者 8
  • [0-9] ——匹配一个 0-9 的数字
  • [0-9]* ——匹配任意长度的数字字符串
  • [a-z] ——匹配一个 a-z 之间的字符
  • [a-z]* ——匹配任意长度的字母字符串
  • [a-c, e-f] ——匹配 a-c 或者 e-f 之间的任意字
1
2
3
# 匹配手机号(虚构号码)
[root@hadoop100 ~]# echo 18888888888 | grep -E ^1[3456789][0-9]{9}$
18888888888

(6)特殊字符:\

  • \ 表示转义,并不会单独使用。
  • 由于所有特殊字符都有其特定匹配模式,当我们想匹配 某一特殊字符本身时(例如,我想找出所有包含 ‘$’ 的行),就会碰到困难。此时我们就要 将转义字符和特殊字符连用,来表示特殊字符本身;
1
2
3
4
5
6
7
[root@hadoop100 shell]# cat diff.sh | grep '\$'
echo '=== $* ==='
for i in "$*"
echo "letter is $i"
echo '=== $@ ==='
for i in "$@"
echo "letter is $i"