[ previous ] [ Contents ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] [ 7 ] [ 8 ] [ 9 ] [ 10 ] [ 11 ] [ 12 ] [ 13 ] [ 14 ] [ 15 ] [ 16 ] [ 17 ] [ 18 ] [ A ] [ B ] [ C ] [ D ] [ next ]


Debian 教程 (已过时的文档)
第 11 章 - 文本工具


head, tail, grep, wc, tr, sed, perl 等等


11.1 正则表达式

正则表达式是对一组字符的描述。此描述可用于在文件中搜索与正则表达式匹配的文本。正则表达式类似于 shell 通配符 (参见 文件名展开 (“通配符”),第 6.6 节),但它们更复杂且更强大。

正则表达式由文本和元字符组成。元字符只是具有特殊含义的字符。元字符包括:. * [] - \ ^ $

如果正则表达式仅包含文本 (没有元字符),则它匹配该文本。例如,正则表达式 'my regular expression' 匹配文本 'my regular expression',仅此而已。正则表达式通常区分大小写。

您可以使用 egrep 命令来显示文件中包含正则表达式的所有行。其语法是

egrep 'regexp' filename1 ... [16]

例如,要查找 GPL 中包含单词 GNU 的所有行,您可以输入

     egrep 'GNU' /usr/doc/copyright/GPL

egrep 会将行打印到标准输出。

如果您想要包含 freedom,后跟一些不确定的文本,然后是 GNU 的所有行,您可以这样做

     egrep 'freedom.*GNU' /usr/doc/copyright/GPL

. 表示 “任何字符”;* 表示 “零个或多个前面的事物”,在本例中是 “零个或多个任何字符”。所以 .* 几乎匹配任何文本。egrep 仅逐行匹配,因此 freedomGNU 必须在同一行。

以下是正则表达式元字符的摘要

.

匹配除换行符之外的任何单个字符。

*

匹配零个或多个前面事物的出现。因此,表达式 a* 匹配 0 个或多个小写字母 a,而 .* 匹配零个或多个字符。

[characters]

括号必须包含一个或多个字符;整个括号表达式从集合中精确匹配一个字符。因此,[abc] 匹配一个 a、一个 b 或一个 c;它不匹配 0 个字符,也不匹配这三个字符以外的字符。

^

将您的搜索锚定在行首。表达式 ^The 仅在行首匹配 The;在 The 之前不能有空格或其他文本。如果您想允许空格,您可以像这样允许 0 个或多个空格字符:^ *The

$

锚定在行尾。end$ 要求文本 end 位于行尾,且没有中间空格或文本。

[^characters]

^ 反转括号字符列表的含义。因此,[^abc] 匹配任何单个字符,除了 a、b 或 c。

[character-character]

您可以在括号字符列表中包含范围。要匹配任何小写字母,请使用 [a-z]。您可以有多个范围;因此,要匹配字母表的前三个或最后三个字母,请尝试 [a-cx-z]。要获取任何字母,任何大小写,请尝试 [a-zA-Z]。您可以将范围与单个字符和 ^ 元字符混合使用;例如,[^a-zBZ] 表示 “除了小写字母、大写 B 或大写 Z 之外的任何内容”。

()

您可以像在数学表达式中一样,使用括号将正则表达式的各个部分分组

|

| 表示 “或” --- 您可以使用它来提供一系列替代表达式。通常您希望将替代项放在括号中,例如:c(ad|ab|at) 匹配 cadcabcat。如果没有括号,它将匹配 cadabat

\

转义任何特殊字符;如果您想查找字面量 *,您输入 \*。反斜杠表示忽略 * 的通常特殊含义。

这里还有一些示例,以帮助您了解情况

c.pe

matches cope, cape, caper

c\.pe

matches c.pe, c.per

sto*p

matches stp, stop, stoop

car.*n

matches carton, cartoon, carmen

xyz.*

matches xyz and anything after it; some tools, like egrep, only match until the end of the line.

^The

matches The at the beginning of a line

atime$

matches atime at the end of a line

^Only$

matches a line which consists solely of the word Only --- no spaces, no other characters, nothing. Only Only is allowed

b[aou]rn

matches barn, born, burn

Ver[D-F]

matches VerD, VerE, VerF

Ver[^0-9]

matches Ver followed by any non-digit

the[ir][re]

matches their, therr, there, theie

[A-Za-z][A-Za-z]*

matches any word which consists of only letters, and at least one letter. Will not match numbers or spaces


[ previous ] [ Contents ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] [ 7 ] [ 8 ] [ 9 ] [ 10 ] [ 11 ] [ 12 ] [ 13 ] [ 14 ] [ 15 ] [ 16 ] [ 17 ] [ 18 ] [ A ] [ B ] [ C ] [ D ] [ next ]


Debian 教程 (已过时的文档)

29 Dezember 2009

Havoc Pennington hp@debian.org