grep -E = egrep
实验前提:
- cp /etc/passwd /mnt
- 切换到mnt目录下,编辑passwd文件中的内容,只保存部分内容即可
1.grep 格式
grep 匹配条件 处理文件
命令 | 作用 |
---|---|
grep root passwd | 过滤root关键字 |
grep ^root passwd | 以root开头 |
grep root$ passwd | 以root结尾 |
grep -i root passwd | 忽略大小写 |
grep -E “<root” passwd | root字符之前不能有字符 |
grep -E “root>” passwd | root字符之后不能有字符 |
grep -数字 | 显示过滤行以及上面几行和下面几行 |
grep -n | 显示匹配的行所在行号 |
grep -A | 显示过滤行以及下面几行 |
grep -B | 显示过滤行以及上面几行 |
grep -v | 反向过滤,显示除了匹配行以外的其他行 |
练习:
- -i与-E 的使用
注意:当没有使用-E 时
- 数字等用法
2.grep字符数量匹配规则
命令 | 作用 |
---|---|
^westos | 以westos开头 |
westos$ | 以westos结尾 |
w. . . .s | w开头s结尾中间4个任意字符 |
. . . . .s | s结尾前面5个任意字符 |
…代表字符的个数
练习:
命令 | 作用 |
---|---|
* | 字符出现0到任意次 |
? | 0到1次 |
+ | 1到任意次 |
{n} | n次 |
{m,n} | m到n次 |
{0,n} | 0-n次 |
{,n} | 0-n次 |
{m,} | 最少m次 |
(lee){2} | ee字符串出现2次 |
练习:
练习脚本:
问题: 请显示系统中能被su命令切换的用户名称
第一次尝试:
[root@xixi ~]# ls /home
liyanqiu westos
[root@xixi ~]#
此命令的缺点在于:不能出现root用户
第二次尝试(脚本):
vim show_login.sh
#!/bin/bash
grep bash$ /etc/passwd
此方法的缺点:有些用户可能是以sh结尾的,这样就会遗漏
最后尝试(脚本)
vim show_login.sh
#!/bin/bash
grep -E "bash$|csh$|tcsh$|csh$" /etc/passwd | cut -d : -f 1