正则表达GREP之练习题

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

 cat /proc/meminfo | grep -o '^S.*'
 egrep "^(s|S)" /proc/meminfo
 grep -e "^s" -e "^S" /proc/meminfo
 grep "^(s|S)" /proc/meminfo
 grep "^[sS]" /proc/meminfo

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

 egrep -v '(/bin/bash)$' /etc/passwd

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

 getent passwd rpc | cut -d: -f7

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

 egrep -o '[0-9]{2,3}' /etc/passwd

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

 egrep '^[[:space:]]{1,}.*' /etc/grub2.cfg

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

 netstat -tan | egrep '(LISTEN)[[:space:]]+$'

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

 cut -d: -f1,3 /etc/passwd

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

 useradd -M bash
 useradd -M testbash
 useradd -M basher
 useradd -M sh
 useradd -M -s /sbin/nologin nologin
 egrep '(^.)\>.\<\1$' /etc/passwd

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

 df | grep -o '\<[0-9]+%.*' | sort -rn

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

 LOGIN_COLOR="\e[1;31m"
 LOW_COLOR="\e[0m"
 for i in $@;do
   echo -e "${i}用户的 UID 是:${LOGIN_COLOR}id $i | cut -d" " -f1 | grep -Eo "[0-9]+"${LOW_COLOR}"
 done
 echo -e "系统默认的Shell环境是:${LOGIN_COLOR}echo $SHELL${LOW_COLOR}"

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

 egrep -o '(/[[:lower:]]+)+' /etc/rc.d/init.d/functions

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

 echo /etc/rc.d/init.d/functions | egrep -o '[^/]+/?$'

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

 echo /etc/rc.d/init.d/ | egrep -Eo '^/.*/$'

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

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

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

 echo 9 | egrep "\b[[:digit:]]{1}\>"
 echo 99 | egrep "\b[1-9][[:digit:]]{1}\>"
 echo 199 | egrep '\b[1][[:digit:]]{1}'
 echo 249 | grep '\b2[0-4][[:digit:]]{1}'
 echo 255 | egrep '\b25[0-5]'

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

  ifconfig | egrep -o '([[:digit:]]{1,3}.){3}[[:digit:]]'

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

  echo welcome to magedu linux | tr -d " " | grep -o '.' | sort | uniq -c | sort -rn

猜你喜欢

转载自blog.51cto.com/12980155/2364302