21. 附加正则表达式


竖线字符|用于指定两个完整子表达式中的任意一个可以出现在位置中。子表达式1|子表达式2匹配子表达式 1 或子表达式 2。

打印包含 101 或 102 的行:

$ sed -n '/101\|102/ p' employee.txt
101,John Doe,CEO
102,Jason Smith,IT Manager

注意:请注意|符号需要用\转义。

打印包含 2 到 3 的数字字符或包含字符串 105 的行:

$ sed -n '/[2-3]\|105/ p' employee.txt
102,Jason Smith,IT Manager
103,Raj Reddy,Sysadmin
105,Jane Miller,Sales Manager

后跟{m}的正则表达式表示前面的字符恰好出现 m 次。

对于本示例,创建以下numbers.txt 文件。

$ vi numbers.txt
1
12
123
1234
12345
123456

打印包含任何数字的行(将打印所有行):

$ sed -n '/[0-9]/ p' numbers.txt
1
12
123
1234
12345
123456

正则表达式后跟{m,n}表示前面的项必须至少匹配 m 次,但不超过 n 次。 mn 的值必须为非负且小于 255。

打印由至少 3 位但不超过 5 位数字组成的行。

$ sed -n '/^[0-9]\{3,5\}$/ p' numbers.txt
123
1234
12345

注意:后跟{m,}的正则表达式是一种特殊情况,它表示前面的项至少出现大于等于 m 次。

\b用于匹配单词边界。 \b匹配单词开头和结尾的任何字符,因此 \bthe\b 会找到 the\bthe 会找到 thethey

创建以下示例文件进行测试。

$ cat words.txt
word matching using: the
word matching using: thethe
word matching using: they

匹配包含整个单词 the 的行:

$ sed -n '/\bthe\b/ p' words.txt
word matching using: the

注意:请注意,如果末尾不指定\b,它将匹配所有行。

匹配包含以 the 开头的单词的行:

$ sed -n '/\bthe/ p' words.txt
word matching using: the
word matching using: thethe
word matching using: they

向后引用可让您对表达式进行分组以供进一步使用。

仅匹配单词 the 重复两次的行:

$ sed -n '/\(the\)\1/ p' words.txt

使用相同的逻辑,正则表达式 \([0-9]\)\1 匹配两个数字,其中两个数字都是相同的数字,例如 11,22,33…