1 grep:文本過濾(模式:pattern)工具; *(grep, egrep, fgrep) 2 sed:stream editor,文本編輯工具; 3 awk:Linux上的實現gawk,文本報告生成器;
grep: Global search REgular expression and Print out the line.git
1 選項: 2 --color=auto: 對匹配到的文本着色顯示; 3 -v: 顯示不可以被pattern匹配到的行; 4 -i: 忽略字符大小寫; 5 -o: 僅顯示匹配到的字符串; 6 -q: 靜默模式,不輸出任何信息; 7 -A #:after, 後#行 8 -B #: before, 前#行 9 -C #:context, 先後各#行 10 11 -E:使用ERE;
基本正則表達式元字符:正則表達式
字符匹配:shell
1 # grep '^{s|S}' /proc/meminfo 2 # grep -i '^s' /proc/meminfo
二、顯示/etc/passwd文件中不以/bin/bash結尾的行;express
1 # grep -v '/bin/bash$' /etc/passwd
三、顯示/etc/passwd文件中ID號最大的用戶的用戶名;centos
1 # sort -t: -k3 -n /etc/passwd | tail -1 | cut -d: -f1
四、若是用戶root存在,顯示其默認的shell程序;bash
1 # id root &> /dev/null && grep "^root\>" /etc/passwd | cut -d: -f7
五、找出/etc/passwd中的兩位或三位數;工具
1 # grep "\<[0-9]\{2,3\}\>" /etc/passwd
六、顯示/etc/rc.d/rc.sysinit文件中,至少以一個空白字符開頭的且後面存非空白字符的行;spa
1 # grep "^[[:space:]]\+[^[:space:]]" /etc/rc.d/rc.sysinit
七、找出"netstat -tan"命令的結果中以'LISTEN'後跟0、1或多個空白字符結尾的行;code
# netstat -tan | grep "LISTEN[[:space:]]*$"
八、添加用戶bash、testbash、basher以及nologin(其shell爲/sbin/nologin);然後找出/etc/passwd文件中用戶名同shell名的行;blog
1 # grep "^\([[:alnum:]]\+\>\).*\1$" /etc/passwd
egrep及擴展的正則表達式
egrep = grep -E
1 # grep -E '^(root|centos|user1)\>' /etc/passwd | cut -d: -f1,3,7
二、找出/etc/rc.d/init.d/functions文件(centos6)中某單詞後面跟一個小括號的行;
# grep -E -o "^[_[:alpha:]]+\(\)" /etc/rc.d/init.d/functions
三、使用echo輸出一絕對路徑,使用egrep取出其基名;
1 # echo "/mnt/sdc" | grep -E -o "[^/]+/?$" | cut -d"/" -f1