grep命令详解

以/etc/passwd为例

过滤出带有某个关键词的行并输出行号

[root@localhost ~]# grep -n 'root' /etc/passwd

过滤出不带有某个关键词的行并输出行号

[root@localhost ~]# grep -n -v 'root' /etc/passwd

过滤出所有包含数字的行

[root@localhost ~]# grep '[0-9]' /etc/passwd193

过滤出所有不包含数字的行

[root@localhost ~]# grep -v '[0-9]' /etc/passwd

去除所有以'#'开头的行

[root@localhost ~]# grep -v '^#' /etc/passwd

去除所有空行和以#开头的行

[root@localhost ~]# grep -v '^$' /etc/passwd|grep -v '^#'

过滤出以英文字母开头的行

[root@localhost ~]# grep '^[a-zA-Z]' /etc/passwd

过滤出以非数字开头的行

[root@localhost ~]# grep '^0-9' /etc/passwd

说明: 在[]里面加^表示取非。过滤任意一个或多个字符

[root@localhost ~]# grep 'r.o' /etc/passwd; grep 'rt' /etc/passwd; grep 'r.t' /etc/passwd

过滤出包含 root 的行以及下面一行

[root@localhost ~]# grep -A1 'root' /etc/passwd194

过滤出包含 root 的行以及上面一行

[root@localhost ~]# grep -B1 'root' /etc/passwd.

. 表示任意一个字符;

表示零个或多个前面的字符;.* 表示零个或多个任意字符,空行也包含在内指定过滤字符次数

[root@localhost ~]# grep 'o{2}' /etc/passwd(3)egrepegrep

工具是 grep 工具的扩展,它可以实现所有 grep 的功能,我们也可以用 grep -E 代替 egrep,下面是一些额外的特殊用法。

[root@localhost ~]# alias egrep='egrep --color'

匹配 1 个或 1 个以上+前面的字符

[root@localhost ~]# egrep 'o+' /etc/passwd

匹配 0 个或者 1 个?前面字符

[root@localhost ~]# egrep 'o?' /etc/passwd

匹配 roo 或者匹配 body195

[root@localhost ~]# egrep 'roo|body' /etc/passwd

用括号表示一个整体,下面例子会匹配 roo 或者 ato

[root@localhost ~]# egrep 'r(oo)|(at)o' /etc/passwd

匹配 1 个或者多个 'oo'

[root@localhost ~]# egrep '(oo)+' /etc/passwd

(4). * + ? 总结

. 表示任意一个字符(包括特殊字符)

*表示零个或多个*前面的字符.

.* 表示任意个任意字符(包含空行)

+表示 1 个或多个+前面的字符

? 表示 0 个或 1 个?前面的字符其中,

+和? grep 不支持,egrep 才支持。

发表评论

后才能评论