NAME
grep, egrep, fgrep, rgrep - print lines matching a pattern
SYNOPSIS
grep [OPTIONS] PATTERN [FILE...]
grep [OPTIONS] [-e PATTERN | -f FILE] [FILE...]
DESCRIPTION
grep searches the named input FILEs (or standard input if no files are named, or if a single hyphen-minus (-) is given as file name) for lines containing a match to the given PATTERN. By default, grep prints the matching lines.
基本用法:
grep pattern files - 搜索 files 中匹配 pattern 的内容
grep -v pattern files - 搜索 files 中不匹配 pattern 的内容
grep -r pattern dir - 递归搜索 dir 中匹配 pattern 的内容
command | grep patten - 搜索 command 输出中匹配 pattern 的内容
-i, --ignore-case
-n, --line-number
-c, --count
-r, --recursive
-v, --invert-match
-E, --extended-regexp
-e PATTERN, --regexp=PATTERN
ldd3$ grep -rin hello *
hello/Makefile:8:obj-m := hello.o
hello/Makefile:16: cp hello.ko $(INSTALLDIR)
hello/hello.c:5:static int hello_init(void)
hello/hello.c:7: printk(KERN_ALERT "Hello, world\n");
hello/hello.c:11:static void hello_exit(void)
ldd3$ ps -ef | grep vim
fan 1889 1 0 Mar03 ? 00:03:57 gvim include/linux/sched.h
fan 7398 4596 0 10:21 pts/5 00:00:00 grep --color=auto vim
$ grep -v "#" Makefile
obj-$(CONFIG_I2C_ARB_GPIO_CHALLENGE) += i2c-arb-gpio-challenge.o
obj-$(CONFIG_I2C_MUX_GPIO) += i2c-mux-gpio.o
obj-$(CONFIG_I2C_MUX_PCA9541) += i2c-mux-pca9541.o
obj-$(CONFIG_I2C_MUX_PCA954x) += i2c-mux-pca954x.o
obj-$(CONFIG_I2C_MUX_PINCTRL) += i2c-mux-pinctrl.o
ccflags-$(CONFIG_I2C_DEBUG_BUS) := -DDEBUG
高级用法:
(1) 在当前目录下的所有文件的文件内容中查找哪个文件的内容中有findcontents(大小写不敏感,列出findcontents所在文件的所在行)——适合于当前目录下的文件及目录数目比较少,如果查找后列出内容过多,将会失去查找意义。grep -rin findcontents *
(2) 如果查找后列出内容过多,就需要用如下命令(只列出findcontents在所在文件的出现次数):
grep -ric findcontents * | grep -v :0
(3) 如果根本不知道文件所在目录,就需要在根目录下进行查找(查找整个硬盘空间),但是由于根目录下某些文件(bin、sbin、boot、dev、initrd、lib)没有查找价值,因而要将其排除在查找范围之外
# cd /
grep -rin findcontents `ls | grep -vE 'bin|boot|dev|initrd|lib'`
1. Grep用法小结
2. [精华] Grep 用法