1、 显示/etc/passwd文件中以bash结尾的行;

#grep --colour=auto "bash$" /etc/passwd

image

 

 

2、 显示/etc/passwd文件中的两位数或三位数;

使用BRE方法

#grep --colour=auto "\<[[:digit:]]\{2,3\}\>" /etc/passwd

image

 

使用ERE方法

# grep --colour=auto -E "\<[[:digit:]]{2,3}\>" /etc/passwd

image

 

 

3、 显示’netstat -tan’ 命令结果中以’LISTEN’后跟0个、1个或多个空白字符结尾的行;

# netstat -ant | grep --color=auto "\<LISTEN.*\>"

image

 

 

4、 添加用户bash、testbash、basher以及nologin用户(nologin用户的shell为/sbin/nologin),而后找出/etc/passwd文件中用户名同shell名相同的行

使用BRE方法

# grep "\(^[[:alpha:]]\+\>\).*\1$" /etc/passwd

image

 

使用ERE方法

# grep -E "(^[[:alpha:]]+\>).*\1$" /etc/passwd

image

 

 

5、 显示当前系统上root、centos或user1用户的默认的shell和UID;

# grep -E "^root|^centos|^user1" /etc/passwd | cut -d: -f1,3,7

image

 

 

6、 找出/etc/rc.d/init.d/funcations文件中某单词后面跟着一组小括号的行;

使用BRE方法

# grep --color=auto "\<.\+\(()\)" /etc/rc.d/init.d/functions

image

 

使用ERE方法

# grep -E --color=auto "\<.+(\(\))" /etc/rc.d/init.d/functions

image

 

 

 

7、 使用echo输出一个路径,而后用egrep找出其路径基名,注意,即使结尾是/ 也要求能找出基名

进一步地,使用egrep取出其目录名

使用BRE

# echo "/etc/sysconfig/network-scripts/" | grep -o "[^/]\+\/\?$" | grep --color=auto "[^/]\+"

image

 

使用ERE

# echo "/etc/sysconfig/network-scripts/" | grep -Eo "[^/]+\/?$" | grep -E --color=auto "[^/]+"

image

 

只用grep or egrep显示路径目录名 我只找到一个特解--使用-P的零宽断言

# echo "/etc/sysconfig/network" | grep -P --color=auto '^/.*(?=/)'

image

说是特解,是因为这种解法要求路径最后不能以 / 结尾

谁有更好的解法,求教

 

 

 

8、 找出ifconfig命令执行结果中1-255之间的数字

# ifconfig | grep -E --color=auto '\<[1-9]\>|\<[1-9][0-9]\>|\<1[0-9][0-9]\>|\<2[0-9][0-5]\>'

image