Contents

使用sed插入带空格的行

1. 概述

sed 命令是我们可以用来在 Linux 命令行下处理文本的强大武器。 例如,使用sed命令,我们可以从文件中删除一行替换一行 ,或者在文件中插入一个新行

在本教程中,我们将详细了解如何使用sed命令的功能在新行包含空格时插入新行。

2. 问题介绍

首先,我们来看一个输入文件:

$ cat input.txt 
## A new line will be inserted below me:
This is the end of the file.

文件 input.txt看起来很简单。它只包含三行。现在,我们要做的是在第一行之后插入一个新行。当然,新行将包含空格字符。

如果我们仔细考虑这个问题,可能会出现三种情况

  • 首先,空格位于行的中间。
  • 其次,该行有尾随空格。
  • 第三,该行包含前导空格。

使用sed在文件中插入新行有多种方法,例如使用“ a ”命令、“ i ”命令或替换命令“ s ”。

sed的“ a ”命令和“ i ”命令非常相似。唯一的区别是**“ i ”在地址之前插入新行,而“ a ”将在地址之后追加新行**。

在本教程中,我们将重点关注 sed的“ a ”命令。

接下来,我们将介绍这三个场景,并说明如何使用sed 插入带空格的行。

3. 在中间插入一条带空格的线

现在,让我们使用sed的“ a ”命令在文件的第二行插入一个带空格的新行:

$ sed '1 aI am the new line.' input.txt 
A new line will be inserted below me:
## I am the new line.
This is the end of the file.

如上面的输出所示,该命令可以直接运行。

命令中的“ 1 ”是地址,表示第一行。

因此,我们可以将命令sed ‘1 a…’ 翻译为“当行号为 1 时,在其后追加新行”

接下来,让我们看看当要插入的行有尾随空格时该命令是否仍然有效。

4. 插入带有尾随空格的行

现在,让我们添加一些尾随空格并尝试相同的命令。我们将使用-e选项将sed*命令的输出通过管道传输到cat 命令, 以便我们可以轻松地验证尾随空格*:

$ sed '1 aI am the new line with trailing spaces   ' input.txt | cat -e
A new line will be inserted below me:$
## I am the new line with trailing spaces   $
This is the end of the file.$

这一次,如上面的输出所示,同样的命令也适用于这种情况。

5. 插入带前导空格的行

首先,让我们再次尝试相同的命令,并希望它适用于前导空格的情况:

$ sed '1 a  I am the new line with leading and trailing spaces   ' input.txt | cat -e
A new line will be inserted below me:$
## I am the new line with leading and trailing spaces   $
This is the end of the file.$

正如我们所见,输出中的前导空格已经消失。因此,该命令没有像我们预期的那样工作。

*为了解决这个问题,我们需要在“ a ”命令之后添加一个反斜杠“ * ” :

$ sed '1 a\  I am the new line with leading and trailing spaces   ' input.txt | cat -e
A new line will be inserted below me:$
##   I am the new line with leading and trailing spaces   $
This is the end of the file.$

我们可能认为我们必须使用反斜杠转义前导空格。然而,这是一个误解。因此,有必要明确反斜杠在这里的作用。

6. 了解sed  “ a ”和“ i ”命令后的反斜杠

我们已经了解到 sed的“ a ”和“ i ”命令可以插入或追加新行。

a ”或“ i ”命令后的反斜杠字符不能用作转义序列 的一部分,例如*\t作为制表符或\n*作为换行符。相反,它表示我们要插入的新行中文本的开头

即使反斜杠和新行的第一个字符一起可能匹配转义序列,sed也不会将该组合解释为转义序列。 也许,一个例子可以快速解释它:

$ sed '1 a\n (1) and \n (2)' input.txt
A new line will be inserted below me:
n (1) and 
##  (2)
This is the end Of the file.

在这个测试中,我们有两次出现“ \n ”。第二个被解释为换行符,因为它是内容的一部分。

但是,sed将第一个“ \n ”解释为常规“ n ”字符,因为反斜杠只是标记了新内容的开始。

当我们使用 sed的“ a ”或“ i ”命令时,最好在新内容之前加上反斜杠。