次数匹配
扩展正则表达式
对比
扩展正则表达式
扩展正则表达式

有些难
扩展正则表达式

练习

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

[[email protected] ~]#grep -i “^s” /proc/meminfo

[[email protected] ~]#grep “^[Ss].*” /proc/meminfo

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

[[email protected] ~]#cat /etc/passwd | grep -v “/bin/bash$”

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

[[email protected] ~]#cat /etc/passwd | grep “^rpc\>” | cut -d: -f7

/sbin/nologin

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

[[email protected] ~]#cat /etc/passwd | grep -wo “[[:digit:]]{2,3}”

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

[[email protected] ~]#cat /etc/grub2.cfg | grep “^[[:space:]].[^[:space:]].

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

[[email protected] data]#netstat -tan | grep “LISTEN[[:space:]]*$”

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

[[email protected] data]#cat /etc/passwd | cut -d: -f1,3 | grep “:[1-9][0-9]{,2}$”

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

[[email protected] ~]#cat /etc/passwd | grep “^(.+):.*/\1$”

[[email protected] ~]#cat /etc/passwd | grep “^(.):./\1$”

sync:x:5:0:sync:/sbin:/bin/sync

shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown

halt:x:7:0:halt:/sbin:/sbin/halt

bash:x:1001:1001::/home/bash:/bin/bash

nologin:x:1005:1005::/home/nologin:/sbin/nologin

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

[[email protected] ~]#df | grep “/dev/sd” | grep -o “[0-9]*%” | sort -nr

15%

8%

1%

练习

1、显示三个用户root、mage、qjy的UID和默认shell

[[email protected] ~]#cat /etc/passwd | egrep -w “^(root|mage|qjy)” | cut -d: -f1,3,7

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

[[email protected] ~]#cat /etc/rc.d/init.d/functions | grep “^[[:alpha:]_].*()”

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

[[email protected] ~]#echo /etc/rc.d/init.d/functions | egrep -o “[^/]*/?$”

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

echo /etc/rc.d/init.d/functions | egrep -o “./[^$]” | egrep -o “./”

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

last | egrep root | egrep -wo “[0-9]+.[0-9]+.[0-9]+.[0-9]+” | sort | uniq -c | sort -nr

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

[[email protected] ~]#egrep -w [0-9]

[[email protected] ~]#egrep -w [1-9][0-9]

[[email protected] ~]#egrep -w 1[0-9] [0-9]

[[email protected] ~]#egrep -w 2[0-4][0-9]

[[email protected] ~]#egrep -w 25[0-5]

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

[[email protected] ~]#ifconfig | egrep -wo “(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])”

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

[[email protected] ~]#echo “welcome to magedu linux” | egrep -o [a-z’ ‘] | sort | uniq -c | sort -nr

[[email protected] ~]#echo “welcome to magedu linux” | egrep -o . | sort | uniq -c | sort -nr

转载于:https://blog.51cto.com/7981477/2348908

相关文章: