开发手册 欢迎您!
软件开发者资料库

流编辑器 - 特殊字符

流编辑器特殊字符 - 学习流编辑器编程以及如何开发环境,工作流,基本语法,循环,分支,模式缓冲区,模式范围,基本命令,特殊字符,字符串,管理模式,正则表达式,有用的配方。

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.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:]] * $ 找到最后一个数字的出现.在"正则表达式"一章中,我们将探讨有关正则表达式的更多信息.