grep 命令用法

Grep : g (globally) search for a re (regular expression ) and p (print ) the results.

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 用法

3. Unix/Linux 命令速查表

4. 15 Practical Grep Command Examples In Linux / UNIX

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值