流编辑器 - 基本语法

本章介绍SED支持的基本命令及其命令行语法.可以用以下两种形式调用SED:

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


第一个表单允许在线指定命令,它们用单引号括起来.后者允许指定包含SED命令的脚本文件.但是,我们可以多次使用两种形式. SED提供各种命令行选项来控制其行为.

让我们看看如何指定多个SED命令. SED提供删除命令来删除某些行.让我们删除第1行,第2行和第5行.暂时忽略delete命令的所有细节.稍后我们将讨论有关delete命令的更多信息.

首先,使用 cat 命令显示文件内容.

[jerry]$ cat 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仅删除某些行.在这里,要删除三行,我们使用-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的第二种形式.

首先,创建一个包含SED命令的文本文件.为了便于理解,让我们使用相同的SED命令.

[jerry]$ echo -e "1d\n2d\n5d" > commands.txt 
[jerry]$ cat commands.txt


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

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支持以下标准选项:

  • -n:模式缓冲区的默认打印.例如,以下SED命令不显示任何输出:

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

  • [jerry]$ sed -e '' -e 'p' quote.txt
在执行上述代码时,您会得到以下结果: 
There is only one thing that makes a dream impossible to achieve: the fear of failure. 
 - Paulo Coelho, The Alchemist
  • -f

[jerry]$ echo "p" > commands 
[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


GNU特定选项

让我们快速浏览GNU特定的SED选项.请注意,这些选项是GNU特定的;并且可能不受SED的其他变体的支持.在后面的部分中,我们将更详细地讨论这些选项.

  • -n, -  quiet, -  silent:与标准-n选项相同.

  • -e script, -  expression = script:与标准-e选项相同.

  • -f script-file, -  file = script-file:与标准-f选项相同.

  • - -follow-symlinks:如果提供此选项,则在编辑文件时,SED会遵循符号链接.

  • -i [SUFFIX], -  in- place [= SUFFIX]:此选项用于编辑文件.如果提供了后缀,则会备份原始文件,否则会覆盖原始文件.

  • -l N, -  line-lenght = N :此选项将l命令的行长度设置为N个字符.

  • -  posix:此选项禁用所有GNU扩展.

  • -r, -  regexp-extended:此选项允许使用扩展正则表达式而不是基本正则表达式.

  • -u, -  unbuffered:当提供此选项时,SED从输入文件加载最少量的数据并更频繁地刷新输出缓冲区.当你不想等待输出时,它对编辑"tail -f"的输出很有用.

  • -z, -  null-data :默认情况下,SED用换行符分隔每一行.如果提供了NULL-data选项,则它将行分隔为NULL字符.