egrep及扩展的正则表达式
egrep = grep -E
egrep [OPTIONS] PATTERN [FILE...]
扩展正则表达式的元字符:
字符匹配:
.
[]
[^]
次数匹配:
*
?: 0或1;
+:1次或多次;
{m}:匹配m次;
{m,n}:至少m,至多n次;
锚定:
^
$
<, \b
>, \b
分组:
()
后向引用:\1, \2, ...
或者:
a|b
C|cat: C或cat
演示例子仅参考(方法不唯一):
1、显示当前系统root或user1用户的默认shell和UID;
[root@ansible ~]# egrep '^(root|xsc)\>' /etc/passwd | cut -d : -f1,3,7
root:0:/bin/bash
xsc:1000:/bin/bash
2、找出/etc/rc.d/init.d/functions文件(centos6)中某单词后面跟一个小括号的行;
[root@ansible ~]# grep -E -o "^[_[:alpha:]]+\(\)" /etc/rc.d/init.d/functions
checkpid()
__kill_pids_term_kill_checkpids()
__kill_pids_term_kill()
__pids_var_run()
__pids_pidof()
daemon()
killproc()
pidfileofproc()
pidofproc()
status()
echo_success()
echo_failure()
echo_passed()
echo_warning()
update_boot_stage()
success()
failure()
passed()
warning()
action()
strstr()
is_ignored_file()
is_true()
is_false()
apply_sysctl()
3、使用echo输出一绝对路径,使用egrep取出其基名;
root@ansible ~]# echo /bin/etc/ > test.txt
[root@ansible ~]# cat test.txt
/bin/etc/
[root@ansible ~]# grep -E -o "[^/]+/?$" test.txt
etc/
[root@ansible ~]# grep -E -o "[^/]+" test.txt
bin
etc
[root@ansible ~]# echo /bin/etc/ > test.txt
[root@ansible ~]# grep -E -o "[^/]+" test.txt
bin
etc
[root@ansible ~]# grep -E -o "[^/]+/?$" test.txt
etc/
[root@ansible ~]# grep -E -o "[^/]+/?$" test.txt | cut -d / -f1
etc
进一步地:使用egrep取出路径的目录名,类似于dirname命令的结果;
[root@ansible ~]# grep -E -o "^/[[:alpha:]]+/+" test.txt | cut -d / -f 2
bin
4、找出ifconfig命令结果中1-255之间的数值;
ifconfig | grep -E -o "([1-9]|[1-9][0-9]|[1][0-9]{1,2}|[1][0-5]{1,2})"
5、找出ifconfig命令结果中的IP地址;
[root@ansible ~]# ifconfig | grep -E -o "(([1-9]|[1-9][0-9]|[1][0-9]{1,2}|[2][0-5]{1,2})\.)([0-9]{1,3}\.){2}(([1-9]|[1-9][0-9]|[1][0-9]{1,2}|[2][0-5]{1,2}))"
172.26.0.20
172.26.0.255
127.0.0.1