当前位置 主页 > 服务器问题 > Linux/apache问题 >
rep / egrep
语法: grep [-cinvABC] 'word' filename
-c :打印符合要求的行数
-i :忽略大小写
-n :在输出符合要求的行的同时连同行号一起输出
-v :打印不符合要求的行
-A :后跟一个数字(有无空格都可以),例如 A2则表示打印符合要求的行以及下面两行
-B :后跟一个数字,例如 B2 则表示打印符合要求的行以及上面两行
-C :后跟一个数字,例如 C2 则表示打印符合要求的行以及上下各两行
把包含 ‘halt' 的行以及这行下面的两行都打印出。
[root@localhost ~]# grep -A2 'halt' /etc/passwd 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
把包含 ‘halt' 的行以及这行上面的两行都打印出。
[root@localhost ~]# grep -B2 'halt' /etc/passwd sync:x:5:0:sync:/sbin:/bin/sync shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown halt:x:7:0:halt:/sbin:/sbin/halt
把包含 ‘halt' 的行以及这行上面和下面的各两行都打印出。
过滤出带有某个关键词的行并输出行号
[root@localhost ~]# grep -n 'root' /etc/passwd 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 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 HOME=/