UbuntuHelp:Grep/zh

出自Ubuntu中文

[编辑] What Is grep? (Grep是什么东西?)

Grep is a command line tool that allows you to find a string in a file or stream. It can be used with Regular expression to be more flexible at finding strings.

Grep是一个用来从文件或数据流中查找字符串的命令行工具,通过结合正则表达式Grep亦能获得更加灵活的匹配效果。

[编辑] How To Use grep (如何使用Grep)

In the simplest case, grep can simply be invoked like this :

举一个最简单的Grep使用例子:

% grep 'STRING' filename

This is OK but it does not show the true power of grep. First this only looks at one file. A cool example of using grep with multiple file would be to find all files in a directory that contains the name of a person. This can be easily accomplished using a grep in the following way :

我们可以使用Grep来简单地从一个文件中查找一个特定的字符串,但这仅仅最简单的功能而已。

% grep 'Nicolas Kassis' *

Notice the use of single quotes; This are not essential but in this example it was required since the name contains a space. Double quotes could also have been used in this example. Now lets use some regular expressions...

[编辑] Grep Regular Expression

grep can search for complicated pattern to find what you need. Here is a list of some of the special characters used to create a regular expression:

Grep Regular Expression
^ <td><td>Denotes the beginning of a line (表示行开头</td><td></td>)
$ <td><td>Denotes the end of a line (表示行结尾</td><td></td>)
. <td><td>Matches any one characters (匹配任意字符</td><td></td>)
* <td><td>Matches 0 or more of the previous characters (匹配0个或多个前面出现的字符</td><td></td>)
.* <td><td>Matches any number or type of characters (匹配0或任意多个字符</td><td></td>)
[] <td><td>Matches on character for the one listed in the the Square brackets (匹配中括号中其中一个字符</td><td></td>)
[^] <td><td>Does not match any characters listed (匹配除中括号中所列字符外的所有字符</td><td></td>)
\/ <td><td>Denotes the beginning and end (respectively) of a word (匹配一个单词的开头与结尾</td><td></td>)

So an example of a regular expression search would be

一下是一个使用了正则表达式的Grep例子

% grep "\<[A-Za-z].*" file

This will search for any word which begins with a letter upper or lower case. For more details check: