grep用法

语法: grep  [-cinvhlsABC]  'word'  filename

-c :打印符合要求的行数

-n :在输出匹配行及行号一起输出

-v :打印不符合要求的行(取反)

-i :不区分大小写(只适用于单字符)

-h :查询多文件时不显示文件名

-l :查询多文件时只输出包含匹配字符的文件名

-s :不显示不存在或无匹配文本的错误信息

-A :后跟一个数字,例如 –A2则表示打印符合要求的行以及下面两行

-B :后跟一个数字,例如 –B2 则表示打印符合要求的行以及上面两行

-C :后跟一个数字,例如 –C2 则表示打印符合要求的行以及上下各两行

实例解析

[root@localhost ~]# grep -A2 'halt' /etc/passwd #把包含halt的行及其下面的两行输出halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin


[root@localhost ~]# grep -B2 'halt' /etc/passwd #把包含halt的行及其上面的两行输出
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt


[root@localhost ~]# grep -C2 'halt' /etc/passwd  #把包含halt的行及其上、下的各两行输出sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin


[root@localhost ~]# grep -n 'root' /etc/passwd  #过滤出带有root关键字的行及行号

1:root:x:0:0:root:/root:/bin/bash
11:operator:x:11:0:operator:/root:/sbin/nologin


[root@localhost ~]# grep -nv 'nologin' /etc/passwd #过滤不带有nologin的行及行号1:root:x:0:0:root:/root:/bin/bash
6:sync:x:5:0:sync:/sbin:/bin/sync
7:shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
8:halt:x:7:0:halt:/sbin:/sbin/halt
26:test:x:511:511::/home/test:/bin/bash
27:test1:x:512:511::/home/test1:/bin/bash


[root@localhost ~]# grep '[0-9]' /etc/inittab    #过滤出所有包含数字的行

# upstart works, see init(5), init(8), and initctl(8).
#   0 - halt (Do NOT set initdefault to this)
#   1 - Single user mode
#   2 - Multiuser, without NFS (The same as 3, if you do not have networking)
#   3 - Full multiuser mode
#   4 - unused
#   5 - X11
#   6 - reboot (Do NOT set initdefault to this)
id:3:initdefault:


[root@localhost ~]# grep -v '[0-9]' /etc/inittab   #过滤出所有不包含数字的行

# inittab is only used by upstart for the default runlevel.
#
# ADDING OTHER CONFIGURATION HERE WILL HAVE NO EFFECT ON YOUR SYSTEM.
#
# System initialization is started by /etc/init/rcS.conf
#
# Individual runlevels are started by /etc/init/rc.conf
#
# Ctrl-Alt-Delete is handled by /etc/init/control-alt-delete.conf
#
# Terminal gettys are handled by /etc/init/tty.conf and /etc/init/serial.conf,
# with configuration in /etc/sysconfig/init.
#
# For information on how to write upstart event handlers, or how
#
# Default runlevel. The runlevels used are:
#


[root@localhost ~]# grep -v '^#' /etc/inittab    #把所有以‘#’开头的行去除

id:3:initdefault:


[root@localhost ~]# grep -v '^#' /etc/crontab |grep -v '^$' #去除所有空行和以#开头的行

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root