Stream 编辑器 - 特殊字符

SED 提供了两个特殊字符,它们被视为命令。 本章说明这两个特殊字符的用法。


= 命令

"="命令处理行号。 下面给出的是"="命令的语法:

[/pattern/]= 
[address1[,address2]]=

= 命令将行号及其内容写入标准输出流。 以下示例说明了这一点。

[jerry]$ sed '=' books.txt 

执行上述代码,得到如下结果:

1 
1) A Storm of Swords, George R. R. Martin, 1216 
2 
2) The Two Towers, J. R. R. Tolkien, 352 
3 
3) The Alchemist, Paulo Coelho, 197 
4 
4) The Fellowship of the Ring, J. R. R. Tolkien, 432 
5 
5) The Pilgrimage, Paulo Coelho, 288 
6 
6) A Game of Thrones, George R. R. Martin, 864

让我们打印行号和前四行的内容。 以下命令打印带行号的前四行,其余不带行号。

[jerry]$ sed '1, 4=' books.txt 

执行上述代码,得到如下结果:

1 
1) A Storm of Swords, George R. R. Martin, 1216 
2 
2) The Two Towers, J. R. R. Tolkien, 352 
3 
3) The Alchemist, Paulo Coelho, 197 
4 
4) The Fellowship of the Ring, J. R. R. Tolkien, 432 
5) The Pilgrimage, Paulo Coelho, 288 
6) A Game of Thrones, George R. R. Martin, 864

此外,我们可以指示 SED 在模式匹配成功时打印行号。 下面的示例打印包含模式"Paulo"的行号。

[jerry]$ sed '/Paulo/ =' books.txt 

执行上述代码,得到如下结果:

1) A Storm of Swords, George R. R. Martin, 1216 
2) The Two Towers, J. R. R. Tolkien, 352 
3 
3) The Alchemist, Paulo Coelho, 197 
4) The Fellowship of the Ring, J. R. R. Tolkien, 432 
5 
5) The Pilgrimage, Paulo Coelho, 288 
6) A Game of Thrones, George R. R. Martin, 864

你能猜出下面的 SED 命令是做什么的吗?

[jerry]$ sed -n '$ =' books.txt

执行上述代码,得到如下结果:

6 

是的。 它计算文件中存在的总行数。 让我们揭开代码的神秘面纱。 在命令部分,我们使用"$ ="打印最后一行的行号及其内容。 但是我们还提供了 -n 标志,它禁止默认打印模式缓冲区。 因此,仅显示最后的行号。


& 命令

SED 支持特殊字符 &。每当模式匹配成功时,这个特殊字符就会存储匹配的模式。 它通常与替换命令一起使用。 让我们看看如何利用这个高效的特性。

book.txt 文件中的每一行都有编号。 让我们在每一行的开头添加单词书号。 以下示例说明了这一点。

[jerry]$ sed 's/[[:digit:]]/Book number &/' books.txt

执行上述代码,得到如下结果:

Book number 1) A Storm of Swords, George R. R. Martin, 1216 
Book number 2) The Two Towers, J. R. R. Tolkien, 352 
Book number 3) The Alchemist, Paulo Coelho, 197 
Book number 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 
Book number 5) The Pilgrimage, Paulo Coelho, 288 
Book number 6) A Game of Thrones, George R. R. Martin, 864 

这个例子非常简单。 首先,我们搜索第一次出现的数字,即行号(这就是我们使用 [[:digit:]] 的原因),SED 自动将匹配的模式存储在特殊字符 & 中。在第二步中,我们在每个匹配的模式之前插入单词 Book number,即,在每一行之前。

让我们再举一个例子。 在 book.txt 文件中,最后一位数字表示书的页数。 让我们在此之前添加"Pages ="。为此,请找到最后一次出现的数字并将其替换为"Pages = &"。 在这里 & 存储匹配的模式,即页数

[jerry]$ sed 's/[[:digit:]]*$/Pages = &/' books.txt 

在执行上述语法时,您会得到以下结果:

1) A Storm of Swords, George R. R. Martin, Pages = 1216 
2) The Two Towers, J. R. R. Tolkien, Pages = 352 
3) The Alchemist, Paulo Coelho, Pages = 197 
4) The Fellowship of the Ring, J. R. R. Tolkien, Pages = 432 
5) The Pilgrimage, Paulo Coelho,Pages = 288 
6) A Game of Thrones, George R. R. Martin, Pages = 864 

暂时,只需要记住 [[:digit:]]*$ 会找到最后一次出现的数字。 在"正则表达式"一章中,我们将探索更多关于正则表达式的知识。