grep练习题

来源:互联网 发布:qq音乐 for ubuntu 编辑:程序博客网 时间:2024/06/05 14:44

1 、显示/proc/meminfo 文件中以大小s 开头的行( 要求:使用两
种方法)

grep  "^[sS]" /proc/meminfogrep -i "^[s]" /proc/meminfogrep -e "^s" -e "^S" /proc/meminfogrep "^\(s\|S\)" /proc/meminfo

2 、显示/etc/passwd 文件中不以/bin/bash 结尾的行

grep -v "/bin/bash$" /etc/passwd

3 、显示用户rpc 默认的shell 程序

grep "^rpc\>" /etc/passwd|cut -d: -f7

4 、找出/etc/passwd 中的两位或三位数

grep -o "[[:digit:]]\{2,3\}" /etc/passwd

5 、显示CentOS7 的/etc/grub2.cfg 文件中,至少以一个空白
字符开头的且后面存非空白字符的行

grep "^[[:space:]]\+[^[:space:]]\+" /etc/grub2.cfg

6 、找出“netstat -tan” 命令的结果中以‘LISTEN’ 后跟任意多
个空白字符结尾的行

netstat -tan|grep "\bLISTEN[[:space:]]*"

7 、显示CentOS7 上所有系统用户的用户名和UID

cat /etc/passwd|cut -d: -f1,3|egrep "\b[1-9][0-9]{0,2}\b"cat /etc/passwd|cut -d: -f1,3|egrep  "\b[[:digit:]]{1,3}\b"|grep  -v "\b0\b"

8 、添加用户bash 、testbash 、basher 、sh 、nologin( 其shell
为 为/sbin/nologin), 找出/etc/passwd 用户名同shell 名的行

useradd -M bashuseradd -M testbashuseradd -M basheruseradd -M shuseradd -M -s /sbin/nologin nologincat /etc/passwd | egrep "(^[[:alnum:]]*\>).*\b\1$\b"cat /etc/passwd | egrep "(^[[:alnum:]]*\>).*/\1$"egrep "(^.*)\>.*\<\1$" /etc/passwd egrep "(^.*)\>.*/\1$" /etc/passwd

9 、利用df 和grep,取出磁盘各分区利用率,并从大到小排序

df |grep -o "\<[0-9]*%.*" -o|sort -n

10 、显示三个用户root 、mage 、wang 的UID 和默认shell

cat /etc/passwd|egrep "^\<root|mage|wang\>" |cut -d: -f1,3,7

11 、找出/etc/rc.d/init.d/functions 文件中行首为某单词(包 包
括下划线) 后面跟一个小括号的行

egrep -o  '^([[:alnum:]]|_)+\(\)' /etc/rc.d/init.d/functions egrep -o  '^[[:alnum:]_]+\(\)' /etc/rc.d/init.d/functions egrep -o  '^[a-zA-Z0-9_]+\(\)' /etc/rc.d/init.d/functions egrep -o  '^.*\>\(\)' /etc/rc.d/init.d/functionsegrep -o  '^.*\b\(\)' /etc/rc.d/init.d/functions

12 、使用egrep 取出/etc/rc.d/init.d/functions 中其基名

echo /etc/rc.d/init.d/functions |grep -Eo "[^/]+$" 只能处理文件echo /etc/rc.d/init.d/functions |grep -Eo "[[:alnum:]]+$" 只能处理文件echo /etc/rc.d/init.d/ |grep -Eo "[^/]+/?$" 通用方法

13 、使用egrep 取出上面路径的目录名

echo "/etc/rc.d/init.d/functions" |egrep -o "/.*/"echo "/etc/rc.d/init.d/" |egrep -o "/.*/[[:alnum:]]"|grep -o ".*/" 通用方法

14 、统计last 命令中以root 登录的每个主机IP 地址登录次数

last |egrep "\<root\>" |tr -s " "|cut -d " " -f1,3|sort|uniq -c

15、利用扩展正则表达式分别表示0-9 、10-99 、100-199、 、
200-249 、250-255

egrep "\b[[:digit:]]{1}\>" f1egrep "\b[1-9][[:digit:]]{1}\>" f1egrep "\b1[[:digit:]]{2}\>" f1egrep "\b2[0-4][[:digit:]]{1}\>" f1egrep "25[0-5]" f1

16、显示ifconfig 命令结果中所有IPv4 地址

ifconfig |grep "inet\b"|tr -s " "|cut -d " " -f3ifconfig| grep -o '\(\([0-9]\|[1-9][0-9]\|1[0-9]\{2\}\|2[0-4][0-9]\|25[0-5]\)\.\)\{3\}\([0-9]\|[1-9][0-9]\|1[0-9]\{2\}\|2[0-4][0-9]\|25[0-5]\)'

17、将此字符串:welcome to magedu linux 中的每个字符
去重并排序,重复次数多的排到前面

echo "welcome to magedu linux" |grep -o "[[:alpha:]]"|sort|uniq -c|sort -nr