如何使用grep命令进行搜索

时间:2019-08-20 17:58:20  来源:igfitidea点击:

grep命令在搜索文件中的关键字时非常有用。

不使用任何标志,grep命令将显示文件中与关键字匹配的行。

例如,如果我想搜索关键字“test”,它将显示与关键字“test”相似的结果,如 testing、loadtesting、 test 。

例如, 在下面的例子中,你可以看到它用相似的词而不是确切的词来显示结果。

Hyman@theitroad:/tmp$ cat red 
this is a test
file for doing testing
by redtest team
this is called redtesting
bla bla bla 
bla 2 bla 3 bla 4
ok ok test the file
Hyman@theitroad:/tmp$ 
Hyman@theitroad:/tmp$ 
Hyman@theitroad:/tmp$ grep test red
this is a test
file for doing testing
by redtest team

如何在文件中精确查找关键字

使用 -w标志可以在查找精确匹配。

grep -w keyword fileName

或者

cat filename | grep -w keyword

例如,只搜索 test关键字

Hyman@theitroad:/tmp$ cat red
this is a test
file for doing testing
by redtest team
this is called redtesting
bla bla bla 
bla 2 bla 3 bla 4
ok ok test the file
Hyman@theitroad:/tmp$ 
Hyman@theitroad:/tmp$ grep -w test red
this is a test
ok ok test the file
Hyman@theitroad:/tmp$