正则表达式
字符匹配
1 2 3
| . 匹配任意单个字符 [] 匹配指定范围内的任意单个字符 [^] 匹配指定范围外的任意单个字符
|
匹配次数
1 2 3 4 5 6 7
| * 匹配前面的字符0次到无数次 ? 匹配前面的字符0次或1次 + 匹配前面的字符至少一次 {n} 匹配前面的字符n次 {m,n} 匹配前面的字符m次到n次 {,n} 匹配前面的字符最多n次 {n,} 匹配前面的字符至少n次
|
位置锚定
1 2 3 4 5 6 7 8 9 10
| ^ 行首 $ 行尾 \> 或 \b 词首 \< 或 \b 词尾
^$ 空行 ^[[:space:]]*$ 空白行 \<PATTERN\> 匹配整个单词
ps:单词是由字母、数字、下划线组成
|
分组及其他
正则表达式练习 1
1、显示/proc/meminfo 文件中以大小 s 开头的行(要求:使用两种方法)
1 2
| grep -i '^s' /proc/meminfo grep -E '^(s|S)' /proc/meminfo
|
2、显示/etc/passwd 文件中不以/bin/bash 结尾的行
1
| grep -E '^/bin/bash$' passwd
|
3、显示用户 rpc 默认的 shell 程序
1
| getent passwd ljk | cut -d: -f8
|
4、找出/etc/passwd 中的两位或三位数
1
| grep -Eo '\<[0-9]{2,3}\>' passwd
|
5、显示 CentOS7 的/etc/grub2.cfg 文件中,至少以一个空白字符开头的且后面有非空白字符的行
1
| grep -E '^[[:space:]]+[^[:space:]]+' /etc/grub2.cfg
|
6、找出“netstat -tan”命令结果中以 LISTEN 后跟任意多个空白字符结尾的行
1
| netstat -tan | grep -E 'LISTEN[[:space:]]+$'
|
7、显示 CentOS7 上所有 UID 小于 1000 以内的用户名和 UID
1 2
| cat /etc/passwd | cut -d: -f1,3 | grep -E '\<[0-9]{1,3}\>' cat /etc/passwd | cut -d: -f1,3 | grep -Ev '\<[0-9]{4,}\>'
|
8、添加用户 bash、testbash、basher、sh、nologin(其 shell 为/sbin/nologin),找出/etc/passwd 用户名和 shell 同名的行
1
| grep -E '^(\<[0-9a-zA-Z_]+\>).*\1$' /etc/passwd
|
9、利用 df 和 grep,取出磁盘各分区利用率,并从大到小排序
1 2
| df | grep '^/dev/sd' | grep -Eo '[0-9]{,3}%' | tr -d % | sort -nr df | grep '^/dev/sd' | tr -s " " % | cut -d% -f5 | sort -nr
|
练习 2
1、显示三个用户 root、mage、wang 的 UID 和默认 shell
2、找出/etc/rc.d/init.d/functions 文件中行首为某单词(包括下划线)后面跟一个小括号的行
1
| grep -E '^[a-zA-Z0-9_]+\(\)' ./functions
|
3、使用 egrep 取出/etc/rc.d/init.d/functions 中其基名
1 2
| grep -E '^\<[0-9a-zA-Z_]+\>\(\)' ./functions | grep -Eo '^\<[0-9a-zA-Z_]+\>' grep -E '^\<[0-9a-zA-Z_]+\>\(\)' ./functions | cut -d ' ' -f 1 | tr -d '()'
|
4、使用 egrep 取出上面路径的目录名
5、统计 last 命令中以 root 登录的每个主机 IP 地址登录次数
1
| last | tr -s ' ' : | cut -d: -f3 | sort | uniq -c | sort -nr
|
6、利用扩展正则表达式分别表示 0-9、10-99、100-199、200-249、250-255
1 2 3 4 5
| grep -E '\<[0-9]{1}\>' a.log grep -E '\<[0-9]{2}\>' a.log grep -E '\<1[0-9]{2}\>' a.log grep -E '\<2[0-4][0-9]\>' a.log grep -E '\<25[0-5]\>' a.log
|
7、显示 ifconfig 命令结果中所有 IPv4 地址
1
| ifconfig | grep -Eo '[0-9]{,3}\.[0-9]{,3}\.[0-9]{,3}\.[0-9]{,3}'
|
8、将此字符串:welcome to magedu linux 中的每个字符去重并排序,重复次数多的排到前面
1
| echo 'welcome to magedu linux' | grep -o '.' | sort | uniq -c | sort -nr
|
9、精确匹配 ip