sed 语法

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

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

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

$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选项指定了三个单独的命令。

$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命令。

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

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

1d 
2d 
5d 

现在指示SED从文本文件读取命令。在这里,我们获得了与上述示例相同的输出。

$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 : 模式缓冲区的默认打印。如以下SED命令不显示任何输出:

$sed -n '' quote.txt 
  • -e : 下一个参数是编辑命令。通过使用此选项,我们可以指定多个命令。让我们将每行打印两次:
$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 <文件名> : 下一个参数是一个包含编辑命令的文件。在下面的示例中,我们通过文件指定打印命令:

$echo "p" > commands 
$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的。在后面的部分中,我们将更详细地讨论这些选项。

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

  • -e script ,-epression=script    : 与标准 -e 选项相同。

  • -f script,--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从输入文件中加载最少的数据量,并更频繁地刷新输出缓冲区。

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