Sed基本语法

sed使用简单,我们可以提供sed命令直接在命令行或具有sed命令的文本文件的形式。本教程讲解调用sed的例子,有这两种方法:

Sed 命令行

以下是我们可以指定单引号在命令行sed命令的格式如下:

sed [-n] [-e] 'command(s)' files 

例子

考虑一下我们有一个文本文件books.txt待处理,它有以下内容:

1) A Storm of Swords, George R. R. Martin, 1216 
2) The Two Towers, J. R. R. Tolkien, 352 
3) The Alchemist, Paulo Coelho, 197 
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文件的完整显示内容如下:

[jerry]$ sed '' books.txt
执行上面的代码,会得到如下结果:
1) A Storm of Swords, George R. R. Martin, 1216
2) The Two Towers, J. R. R. Tolkien, 352
3) The Alchemist, Paulo Coelho, 197
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的delete命令删除某些行。让我们删除了第一,第二和第五行。在这里,要删除给定的三行,我们已经指定了三个单独的命令带有-e选项。

[jerry]$ sed -e '1d' -e '2d' -e '5d' books.txt 

执行上面的代码,会得到如下结果:

3) The Alchemist, Paulo Coelho, 197 
4) The Fellowship of the Ring, J. R. R. Tolkien, 432 
6) A Game of Thrones, George R. R. Martin, 864 

sed脚本文件

下面是第二种形式,我们可以提供一个sed脚本文件sed命令:

sed [-n] -f scriptfile files
首先,创建一个包含在一个单独的行的文本commands.txt文件,每次一行为每个sed命令,如下图所示:

1d 
2d 
5d 

现在,我们可以指示sed从文本文件中读取指令和执行操作。这里,我们实现相同的结果,如图在上述的例子。

[jerry]$ sed -f commands.txt books.txt
执行上面的代码,会得到如下结果:
3) The Alchemist, Paulo Coelho, 197 
4) The Fellowship of the Ring, J. R. R. Tolkien, 432 
6) A Game of Thrones,George R. R. Martin, 864 

sed标准选项

sed支持可从命令行提供下列标准选择。

 -n 选项

这是模式缓冲区的缺省打印选项。 GNU sed解释器提供--quiet,--silent选项作为 -n选项的替代。

例如,下面 sed 命令不显示任何输出:

[jerry]$ sed -n '' quote.txt 
-e 选项

-e选项的编辑选项。通过使用此选项,可以指定多个命令。例如,下面 sed 命令打印每行两次:

[jerry]$ sed -e '' -e 'p' quote.txt
执行上面的代码,会得到如下结果:

There is only one thing that makes a dream impossible to achieve: the fear of failure. 
There is only one thing that makes a dream impossible to achieve: the fear of failure. 
 - Paulo Coelho, The Alchemist 
 - Paulo Coelho, The Alchemist

-f 选项

-f选项是用来提供包含sed命令的文件。例如,我们可以按如下方法通过文件指定一个打印命令:

[jerry]$ echo "p" > commands.txt 
[jerry]$ sed -n -f commands quote.txt
执行上面的代码,会得到如下结果:

There is only one thing that makes a dream impossible to achieve: the fear of failure. 
 - Paulo Coelho, The Alchemist

联系我们

邮箱 626512443@qq.com
电话 18611320371(微信)
QQ群 235681453

Copyright © 2015-2022

备案号:京ICP备15003423号-3