grep 命令是用来在文件中查找含有一些特定文本。 grep有许多参数,它是一个非常有用的命令
语法:grep [选项] pattern [文件名]
在一个文件中,如何查找所有可以匹配关键字的内容?
在下面这个例子中,grep在“/etc/password/” 文件下查找所有含有“John” 的行并全部显示出来
1
2
3
|
# grep John /etc/passwd
jsmith:x:1082:1082:John Smith:
/home/jsmith
:
/bin/bash
jdoe:x:1083:1083:John Doe:
/home/jdoe
:
/bin/bash
|
注:在“/etc/password”下有几行不包含“John”,只有第一行显示了
1
2
|
# grep -v John /etc/passwd
jbourne:x:1084:1084:Jason Bourne:
/home/jbourne
:
/bin/bash
|
在下面这个例子中,显示了在“/etc/password/”下含有“John”的行的总数
1
2
|
# grep -c John /etc/passwd
2
|
1
2
|
# grep -cv John /etc/passwd
39
|
利用“-i”,搜索的时候会忽略大小写
1
2
3
|
# grep -i john /etc/passwd
jsmith:x:1082:1082:John Smith:
/home/jsmith
:
/bin/bash
jdoe:x:1083:1083:John Doe:
/home/jdoe
:
/bin/bash
|
可以利用“-r”来完成。在下面的例子中,在“/home/users/”的子目录下忽略大小写,查找“John”,这会以“文件名:匹配的内容”形式显示。也可以利用参数“-l”,只显示文件名。
1
2
3
4
5
6
7
|
# grep -ri john /home/users
/home/users/subdir1/letter
.txt:John, Thanks
for
your contribution.
/home/users/name_list
.txt:John Smith
/home/users/name_list
.txt:John Doe
# grep -ril john /root
/home/users/subdir1/letter
.txt
/home/users/name_list
.txt
|