|
案例一:
1、显示/proc/meminfo文件中以大小s开头的行;(要求:使用两种方式)
1
2
3
| #grep -i '^s' /proc/meminfo
#grep '^[Ss]' /proc/meminfo
#grep -E '^(s|S)' /proc/meinfo
|
2、显示/etc/passwd文件中不以/bin/bash结尾的行
1
| #grep -v '/bin/bash$' /etc/passwd
|
3、显示用户rpc默认的shell程序
1
| #grep '^\<rpc\>' /etc/passwd | cut -d: -f7
|
4、找出/etc/passwd中的两位或三位数
1
2
| #grep '\<[0-9][0-9]\?\>' /etc/passwd
#grep '\<[0-9]\{2,3\}\>' /etc/passwd
|
5、显示/etc/grub2.cfg文件中,至少以一个空白字符开头的且后面存非空白字符的行
#grep '^[[:space:]]\+.*[^[:space:]]' /etc/grub2.cfg
6、找出"netstat -tan"命令的结果中以'LISTEN'后跟任意个空白字符结尾的行
1
| #netstat -tan '.*LISTEN[[:space:]]*$'
|
7、添加用户bash、testbash、basher以及nologin(其shell为/sbin/nologin),而后找出/etc/passwd文件中用户名同shell名的行
1
2
| #grep '^\<\(.*\)\>.*/\1$' /etc/passwd
#grep '^\<\(.*\)\>.*\<\1\>$' /etc/passwd
|
案例二:
1、显示当前系统root、mage或wang用户的UID和默认shell
1
| #grep -E '^(root|mage|wang)\>' /etc/passwd |cut -d: -f7
|
2、找出/etc/rc.d/init.d/functions文件中行首为某单词(包括下划线)后面跟一个小括号的行
1
| #grep -E -o '^\<[[:alnum:]_]+\>\(\)' /etc/rc.d/init.d/functins
|
3、使用egrep取出/etc/rc.d/init.d/functions中其基名
1
| #echo "/etc/rc.d/init.d/functions" | grep -E -o '[^/]+/?$'
|
4、使用egrep取出上面路径的目录名
1
| #echo "/etc/rc.d/init.d/functions" | grep -E '(/.*/)'
|
5、统计以root身份登录的每个远程主机IP地址的登录次数
1
| #last | grep -o 'root\>.*\([[:digit:]]\{1,3\}\.\)\{3\}[[:digit:]]\>' | tr -s ' ' | cut -d' ' -f3 | uniq -c
|
6、利用扩展正则表达式分别表示0-9、10-99、100-199、200-249、250-255
1
| #grep -E '\<([0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\>'
|
7、显示ifconfig命令结果中所有IPv4地址
1
| #ifconfig | grep -o '\(\([0-9]\|1[0-9]\|1[0-9]{2}\|2[0-4][0-9]\|25[0-5]\)\.\)\{3\}\([0-9]\|1[0-9]\|1[0-9]{2}\|2[0-4][0-9]\|25[0-5]\)'
|
案例三:
4、取本机ip地址
1
| #ifconfig | grep 'inet addr' | grep -E -o '(([1-9]|1[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-4])\.){3}([1-9]|1[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-4])'
|
5、取各分区利用率的数值
1
| df | grep -o '\<[0-9]\+%'
|
6、统计/etc/init.d/functions 文件中每个单词出现的次数,并按频率从高到低显示
非正则:
1
| #cat /etc/init.d/functions | tr -cs '[:alpha:]' ' ' | tr ' ' '\n' | sort | uniq -c | tr -s ' ' | sort -t ' ' -k 1nr
|
正则加替换:
1
| #cat /etc/init.d/functions | tr '_' ' ' | grep -o '\<[a-zA-Z]\+\>' | sort | uniq -c | tr -s ' ' | sort -t' ' -k2 nr
|
纯正则:
1
| #cat /etc/init.d/functions | grep -o --color '\<\([a-zA-Z_]\)\+\>' | grep --color '\<[#a-zA-Z]\+\>' | sort | uniq -c | grep -o "[0-9]\+[[:space:]][a-zA-Z]\+" | sort -t' ' -k1 -nr
|
7、/etc/rc.d/init.d/functions或/etc/rc.d/init.d/functions/" 取目录名
1
2
3
4
5
| #DIR="/etc/rc.d/init.d/functions"
#DIR1="/etc/rc.d/init.d/functions/"
#echo ${DIR} | grep '\(/.*/\)'
#echo ${DIR1} | tr '/' ' ' | cut -d' ' -f1-$[ `echo $DIR | tr '/' ' ' | wc -w` ] | tr ' ' '/'
echo ${DIR} | grep -o '/.*[^/]' | grep --color -o '/.*/'
|
扩展使用sed命令:
1
| echo "/sdsdf/sgdsg/sdgg/fgdfhdfh/" | sed 's/[^\/]\+\/\?$//g'
|
|
|