您的位置:首页 > 运维架构 > Shell

Linux基础入门及系统管理01-Shell三剑客之egrep及扩展正则表达式15

2014-04-14 09:56 1021 查看
一、正则表达式
1、Basic RegExp:基本正则表达式;
a)元字符:
., [], [^];
b)次数匹配:
*, \?, \{m,n\}, .*;
c)位置锚定:
^, $, \<或(\b), \>或(\b);
d)分组:
\(\), \1, \2, \3,……;
e)grep:-i, -v, -o, --color;
-E:使用扩展正则表达式;
-A:显示匹配行后的行数,如:grep -A 2 'cpu MHz' /proc/cpuinfo;
-B:显示匹配行前的行数,如:grep -B 2 'cpu MHz' /proc/cpuinfo;
-c:显示匹配行的前后行数,如:grep -C 2 'cpu MHz' /proc/cpuinfo;
2、Extened RegExp:扩展正则表达式(grep -E=egrep);
a)元字符:., [], [^],与基本正则表达式相同;
b)次数匹配:*, ?, 与基本正则表达式相同;
+:匹配其前面的字符至少1次,如:grep -E '^[[:space:]]+' /boot/grub.conf;
{m,n}:匹配至少m次,至多n次;
c)位置锚定:^, $, \<, \>,与基本正则表达式相同;
d)分组:(), \1, \2, \3,……;
e)或者,||:or;

练习:
1、找出/proc/cpuinfo文件中的,1位数或2位数;
2、找出/boot/grub/grub.conf文件中的1-255之间的整数;
3、查找当前系统上名字为student(必须出现在行首)的用户的帐号的相关信息,文件为/etc/passwd;
4、找到ifconfig命令中显示的IP地址;
5、获取ifconfig命令显示的IP地址;
6、获取ifconfig命令显示的IPv4地址;
参考答案:

1、grep --color '\<.*[0-9]\{1,2\}\>' /proc/cpuinfo;
2、egrep --color '\<([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\>' /boot/grub/grub.conf;
3、grep --color ‘^student\>’ /etc/passwd或者grep '^\<student\>' /etc/passwd;
4、ifconfig | egrep -o --color '\<([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\>\.\<([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\>\.\<([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\>\.\<([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\>';
5、# ifconfig | egrep --color '\<([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.
([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.
([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.
([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\>' ;
或者
# ifconfig | egrep --color '
(\<([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\>\.){3}\<([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\>' ;
6、# ifconfig | egrep --color
'\<[1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-1][0-9]|22[0-3]\>\.{2}\.\<([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4])\>' ;
二、IPV4
5类:A B C D E,可用的有三类:
1、A类:1-127
2、B类:128-191
3、C类:192-223

三、fgrep:不支持正则表达式 。

本文出自 “Jessen Liu的博文” 博客,请务必保留此出处http://zkhylt.blog.51cto.com/3638719/1395099
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: