練習:
一、顯示/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])\>"