sed 特殊字符

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

= 命令

" ="命令显示行号。以下是" ="命令的语法:

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

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

$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

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

$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"的行号。

$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命令做什么吗?

$sed -n '$=' books.txt

执行上述代码后,您将得到以下输出:

6 

在命令部分,我们使用" $="来打印最后一行的行号及其内容,但是,我们还提供了 -n 标志,该标志禁止模式缓冲区的默认打印,因此,仅显示最后一个行号。

& 命令

SED支持特殊字符&。 每当模式匹配成功时,此特殊字符都会存储匹配的模式。 

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

$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=”。 为此,找到该数字的最后一次出现,并将其替换为“>

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

执行上述语法后,将得到以下输出:

1) A Storm of Swords, George R. R. Martin,>