grep
简介
在grep中,我们有相当于OR和NOT运算符的选项,但没有AND运算符。但是,我们可以使用模式来模拟AND。在本文的例子将有助于理解如何使用grep命令的OR, AND和NOT运算进行文本的搜索。
本文将使用下面的employee.txt文件作为例子讲解:
$ cat employee.txt
100 Thomas Manager Sales $5,000
200 Jason Developer Technology $5,500
300 Raj Sysadmin Technology $7,000
400 Nisha Manager Marketing $9,500
500 Randy Manager Sales $6,000
Grep OR操作符
可以使用下面提供的4种方法来实现grep OR功能。
[jinguang1@localhost ~]$ grep "Tech|Sales" employee.txt
[jinguang1@localhost ~]$ grep "Tech|Sales" employee.txt
100 Thomas Manager Sales $5,000
200 Jason Developer Technology $5,500
300 Raj Sysadmin Technology $7,000
500 Randy Manager Sales $6,000
[jinguang1@localhost ~]$ grep -E "Tech|Sales" employee.txt
100 Thomas Manager Sales $5,000
200 Jason Developer Technology $5,500
300 Raj Sysadmin Technology $7,000
500 Randy Manager Sales $6,000
[jinguang1@localhost ~]$ egrep "Tech|Sales" employee.txt
100 Thomas Manager Sales $5,000
200 Jason Developer Technology $5,500
300 Raj Sysadmin Technology $7,000
500 Randy Manager Sales $6,000
[jinguang1@localhost ~]$ grep -e Tech -e Sales employee.txt
100 Thomas Manager Sales $5,000
200 Jason Developer Technology $5,500
300 Raj Sysadmin Technology $7,000
500 Randy Manager Sales $6,000
Grep AND
grep -E 'pattern1.*pattern2' filename
grep -E 'pattern1.pattern2|pattern2.pattern1' filename
下面的例子将grep所有同时包含“Dev”和"Tech"的行,并且保持包含字符串的相应顺序。
[jinguang1@localhost ~]$ grep -E "Dev.*Tech" employee.txt
200 Jason Developer Technology $5,500
下面的例子将grep所有包含“Manager"和"Sales"的行,且这个字符串可以以任意顺序出现。
[jinguang1@localhost ~]$ grep -E "Manager.Sales|Sales.Manager" employee.txt
100 Thomas Manager Sales $5,000
500 Randy Manager Sales $6,000
[jinguang1@localhost ~]$ grep Manager employee.txt | grep Sales
100 Thomas Manager Sales $5,000
500 Randy Manager Sales $6,000
Grep NOT
使用grep -v选项可以模拟NOT操作符。-v选项为相反匹配设计,它可以match所有不包含指定模式的行。
grep -v 'pattern1' filename
下面的例子中将显示所有不包含“Sales”关键字的行。
[jinguang1@localhost ~]$ grep -v Sales employee.txt
200 Jason Developer Technology $5,500
300 Raj Sysadmin Technology $7,000
400 Nisha Manager Marketing $9,500
下面的例子中将显示所有的Manager和Developer,但忽略Sales。
[jinguang1@localhost ~]$ grep -E "Manager|Developer" employee.txt | grep -v Sales
200 Jason Developer Technology $5,500
400 Nisha Manager Marketing $9,500