正则表达式使用单个字符串来描述、匹配一系列符合某个语法规则的字符串。在很多文 本编辑器里,正则表达式通常被用来检索、替换那些符合某个模式的文本。在 Linux 中,grep, sed,awk 等文本处理工具都支持通过正则表达式进行模式匹配。
一串不包含特殊字符的正则表达式匹配它自己,例如:
- [root@hadoop scripts]# cat /etc/passwd | grep sshd
- sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
^ 匹配一行的开头,例如:
会匹配出所有以 a 开头的行
- [root@hadoop scripts]# cat /etc/passwd | grep ^a
- adm:x:3:4:adm:/var/adm:/sbin/nologin
$ 匹配一行的结束,例如:
会匹配出所有以 c结束的行
- [root@hadoop scripts]# cat /etc/passwd | grep c$
- sync:x:5:0:sync:/sbin:/bin/sync
^$ 匹配什么?
结合-n,可以得出开行行号
- [root@hadoop scripts]# cat daily_archive.sh | grep -n ^$
- 2:
- 9:
- 20:
- 23:
- 26:
- 30:
- 32:
- 35:
- 37:
- 48:
. 匹配一个任意的字符,例如:
- [root@hadoop scripts]# cat /etc/passwd | grep r..t
- root:x:0:0:root:/root:/bin/bash
- operator:x:11:0:operator:/root:/sbin/nologin
- ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
* 不单独使用,他和上一个字符连用,表示匹配上一个字符 0 次或多次,例如:
- [root@hadoop scripts]# cat /etc/passwd | grep ro*t
- root:x:0:0:root:/root:/bin/bash
- operator:x:11:0:operator:/root:/sbin/nologin
- vcsa:x:69:69:virtual console memory owner:/dev:/sbin/nologin
.* 匹配什么?以m开头,中间任意字符串,bash结尾
- [root@hadoop scripts]# cat /etc/passwd | grep ^m.*bash$
- mysql:x:27:27:MySQL Server:/var/lib/mysql:/bin/bash
或者是以a开头,var前后任意,in结尾
- [root@hadoop scripts]# cat /etc/passwd | grep ^a.*var.*in$
- adm:x:3:4:adm:/var/adm:/sbin/nologin
[ ] 表示匹配某个范围内的一个字符,例如
[6,8]------匹配 6 或者 8
[0-9]------匹配一个 0-9 的数字
[0-9]*------匹配任意长度的数字字符串
[a-z]------匹配一个 a-z 之间的字符
[a-z]* ------匹配任意长度的字母字符串
[a-c, e-f]-匹配 a-c 或者 e-f 之间的任意字
- [root@hadoop scripts]# cat /etc/passwd | grep r[a,b]t
- operator:x:11:0:operator:/root:/sbin/nologin
- sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
\ 表示转义,并不会单独使用。由于所有特殊字符都有其特定匹配模式,当我们想匹配 某一特殊字符本身时(例如,我想找出所有包含 '$' 的行),就会碰到困难。此时我们就要 将转义字符和特殊字符连用,来表示特殊字符本身,例如
- [root@hadoop scripts]# cat daily_archive.sh | grep '/\$'
- DEST=/root/archive/$FILE
- tar -czf $DEST $DIR_PATH/$DIR_NAME
需求:开头是1,第二位数字只能是34578,有11位
例如:
- [root@hadoop scripts]# echo "13812345678" | grep ^1[34578][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]$
- 13812345678
- [root@hadoop scripts]# echo "12812345678" | grep ^1[34578][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]$ #第二位数字不在范围内
-
扩展用法-E
- [root@hadoop scripts]# echo "13812345678" | grep -E ^1[34578][0-9]{9}$
- 13812345678