Linux grep命令

grep可以用来在文件中搜索文本,能够接受正则表达式,生成各种格式的输出。

grep的基本用法

(1)搜索包含特定模式的文本行

$ grep pattern filename
this is the line containing pattern

或者

$ grep "pattern" filename
this is the line containing pattern

(2)也可以像下面这样从stdin中读取

$ echo -e "this is a word\nnext line" | grep word
this is a word

(3)单个grep命令也可以对多个文件进行搜索

$ grep "match_text" file1 file2 file3...

(4)用--color选项可以在输出行中着重标记匹配到的单词:

$ grep word filename --color=auto
this is the containing word

(5)grep命令只解释match_text中的某些特殊字符。如果要使用正则表达式,需要添加-E选项——这意味着使用扩展正则表达式。或者也可以使用默认允许的正则表达式的grep命令——egrep。例如:

$ grep -E "[a-z]+" filename

或者

$ egrep “[a-z]+” filename

(6)只输出文件中匹配到的文本部分,可以使用选项-o:

$ echo this is a line. | egrep -o “a-z+\.”
line.

(7)要打印除包含match_pattern行之外的所有行,可使用:

$ grep -v match_pattern file

选项-v可以将匹配结果进行反转

(8)统计文件或文本包含匹配字符串的行数:

$ grep -c "text" filename
10

需要注意的是-c只是统计匹配行的数量,并不是匹配的次数。例如:

$ echo -e "1 2 3 4\nhello\n5 6" | egrep -c "[0-9]"
2

尽管有6个匹配项,但命令只打印出2,这是因为只有两个匹配行。在单行中出现的多次匹配只被统计为一次。

(9)要文件中统计匹配项的数量,可以使用下面的技巧

$ echo -e "1 2 3 4\nhello\n5 6" | egrep -o "[0-9]" | wc -l
6

(10)打印出包含匹配字符串的行号

$ cat sample1.txt
gnu is not unix
linux is fun
bash is art
$ cat cample2.txt
planetlinux
$ grep linux -n sample1.txt
2:linux is fun

或者

$ cat sample1.txt | grep linux -n

如果涉及多个文件,它会随着输出结果打印出文件名:

$ grep linux -n sample1.txt sample2.txt
sample1.txt:2:linux is fun
sample2.txt:2:planetlinux

(11)打印模式匹配所位于的字符或字节偏移:

$ echo gnu is not linux | grep -b -o "not"
7:not

一行中字符串的字符偏移是从该行的第一个字符开始计算,起始值是0。

选项-b总是和-o配合使用。

(12)搜索多个文件并找出匹配文本位于哪一个文件中:

$ grep -l linux sample1.txt sample2.txt
sample1.txt
sample2.txt

和-l相反的选项是-L,它会返回一个不匹配的文件列表。


grep的其他特性

1、递归搜索文件

如果需要在多级目录中对文本进行递归搜索,可以使用:

$ grep "text" . -R -n

命令中的"."指定了当前目录。

例如:

$ cd src_dir
$ grep "test_function()" . -R -n
./miscutils/test.c:16:test_function();

test_function()位于miscutils/test.c的第16行

2、忽略样式中的大小写

选项-i可以使用匹配样式不考虑字符的大小写,例如:

$ echo hello world | grep -i "HELLO"
hello

3、用grep匹配多个样式

在进行匹配的时候通常只指定一个样式。然而,我们可以使用选项-e来指定多个匹配样式:

$ grep -e "pattern1" -e "pattern"

例如:

$ echo this is a line of text | grep -e "this" -e "line" -o
this
line

还有另一种方法也可以指定多个样式。可以提供一个样式文件用于读取样式。在样式文件中逐行写下需要匹配的样式,然后用选项-f执行grep:

$ grep -f pattern_filesource_filename

例如:

$ cat pat_file
hello
cool
$echo hello this is  cool | grep -f pat_file
hello this is cool

4、在grep搜索中指定或排除文件

grep可以在搜索过程中指定或排除某些文件。通过通配符来指定所include文件或exclude文件。

目录中递归搜索所有的.c和.cpp文件:

$ grep "main()" . -r --include *.{c,cpp}

注意,some{string1,string2,string3}会扩展成somestring1 somestring2 somestring3。

在搜索中排除所有的README文件:

$ grep "main()" .  -r --exclude "README"

如果要排除目录,可以使用--exclude-dir选项。

如果需要从文件中读取所需排除的文件列表,使用--exclude-from FILE。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值