练习:
一、显示/proc/meminfo文件中以大写或小写S开头的行;
# grep -i '^s' /proc/meminfo
# grep '^[Ss]' /proc/meminfolinux
# grep -E '^(S|s)' /proc/meminfo正则表达式
二、显示/etc/passwd文件中其默认shell为非/sbin/nologin的用户;
# grep -v "/sbin/nologin$" /etc/passwd | cut -d: -f1shell
三、显示/etc/passwd文件中其默认shell为/bin/bash的用户;
进一步:仅显示上述结果中其ID号最大的用户;
# grep "/bin/bash$" /etc/passwd | sort -t: -k3 -n | tail -1 | cut -d: -f1 bash
四、找出/etc/passwd文件中的一位数或两位数;
# grep "\<[0-9][0-9]\?\>" /etc/passwd
# grep "\<[0-9]\{1,2\}\>" /etc/passwdspa
五、显示/boot/grub/grub.conf中以致少一个空白字符开头的行;
# grep "^[[:space:]]\{1,\}" /boot/grub/grub.confit
六、显示/etc/rc.d/rc.sysinit文件中,以#开头,后面跟至少一个空白字符,然后又有至少一个非空白字符的行;
# grep "^#[[:space:]]\{1,\}[^[:space:]]\{1,\}" /etc/rc.d/rc.sysinitio
七、找出netstat -tan命令执行结果中以'LISTEN'结尾的行;
# netstat -tan | grep "LISTEN[[:space:]]*$"function
八、添加用户bash, testbash, basher, nologin(SHELL为/sbin/nologin),而找出当前系统上其用户名和默认shell相同的用户;
# grep "^\([[:alnum:]]\{1,\}\):.*\1$" /etc/passwd
#grep "^\<\([[:alnum:]]*\)\>.*\1$" /etc/passwdtest
九、扩展题:新建一个文本文件,假设有以下内容:
He like his lover.
He love his lover.
He like his liker.
He love his liker.
找出其中最后一个单词是由此前某单词加r构成的行。
\(l..e\).*\1r [root@linux_basic ~]#grep "\<\(....\)\>.*\1r" hello 扩展
扩展正则表达式:
字符匹配:
.
[]
[^]
次数匹配:
*:匹配其前字符任意次
?: 匹配其前字符0次或1次
+: 匹配其前字符至少1次;
{m}: 匹配其前字符精确匹配m次
{m,n}: 匹配其前字符至少m次,至多n次
{m,}
{0,n}
锚定:
^
$
\<, \b
\>, \b
^$, ^[[:space:]]*$
分组:
()
引用:\1, \2, \3
或者:
a|b: a或者b
con(C|c)at
concat或conCat?
conC|cat conC或cat
grep -E 'PATTERN' FILE...
egrep 'PATTERN' FILE...
练习:使用扩展的正则表达式
十、显示当前系统上root、fedora或user1用户的默认shell;
# grep -E "^(root|fedora|user1):" /etc/passwd | cut -d: -f7
十一、找出/etc/rc.d/init.d/functions文件中某单词后跟一组小括号“()”行;
# grep -o -E "\<[[:alnum:]]+\>\(\)" /etc/rc.d/init.d/functions
#grep -o "\<[[:alnum:]]\{1,\}\>()" /etc/rc.d/init.d/functions
# grep -o -E "\<[[:alpha:]]+\(\)" /etc/rc.d/init.d/functions
[root@linux_basic ~]#echo "/etc/rc.d/init.d/" | grep -o -E "[^/].+/$" . 这里是任意单个字符
etc/rc.d/init.d/
[root@linux_basic ~]#echo "/etc/rc.d/init.d/" | grep -o -E "[^/]+/?$"
init.d/
十二、使用echo命令输出一个路径,然后使用grep取出其基名;
echo "/etc/sysconfig/" | grep -o -E "[[:alnum:]]+/?"
# echo "/etc/sysconfig/" | grep -o -E "[^/]+/?$" | cut -d/ -f1
[root@linux_basic ~]#echo "/etc/rc.d/init.d/" | grep -o "[^/]\{1,\}/\?$"
init.d/
# basename /etc/init.d/rc.d
rc.d
# dirname /etc/init.d/rc.d
/etc/init.d
1三、找出ifconfig命令结果中的1-255之间的数字; # ifconfig | grep -o -E "\<([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\>"