插入和附加文本

插入和附加文本

Content #

·插入(insert)(i)命令会在指定行前增加一行。·附加(append)(a)命令会在指定行后增加一行。两者的费解之处在于格式。这两条命令不能在单个命令行中使用。必须指定是将·行插入还是附加到另一行,其格式如下: sed ‘[address]command\ new line’

new line中的文本会出现在你所指定的sed编辑器的输出位置。记住,当使用插入命令时,文本会出现在数据流文本之前: $ echo “Test Line 2” | sed ‘i\Test Line 1’ Test Line 1 Test Line 2 $ 当使用附加命令时,文本会出现在数据流文本之后: $ echo “Test Line 2” | sed ‘a\Test Line 1’ Test Line 2 Test Line 1 $

要向数据流内部插入或附加数据,必须用地址告诉sed编辑器希望数据出现在什么位置。用这些命令时只能指定一个行地址。使用行号或文本模式都行,但不能用行区间。这也说得通,因为只能将文本插入或附加到某一行而不是行区间的前面或后面。

下面的例子将一个新行插入数据流中第三行之前: $ cat data6.txt This is line number 1. This is line number 2. This is the 3rd line. This is the 4th line. $ $ sed ‘3i\ > This is an inserted line. > ’ data6.txt This is line number 1. This is line number 2. This is an inserted line. This is the 3rd line. This is the 4th line. $ 下面的例子将一个新行附加到数据流中第三行之后: $ sed ‘3a\ > This is an appended line. > ’ data6.txt This is line number 1. This is line number 2. This is the 3rd line. This is an appended line. This is the 4th line. $ 这个过程和插入命令一样,只不过是将新文本行放到指定行之后。如果你有一个多行数据流,想要将新行附加到数据流的末尾,那么只需用代表数据最后一行的美元符号即可: $ sed ‘$a\ > This line was added to the end of the file. > ’ data6.txt This is line number 1. This is line number 2. This is the 3rd line. This is the 4th line. This line was added to the end of the file. $ 同样的方法也适用于在数据流的起始位置增加一个新行。这只要在第一行之前插入新行就可以了。要插入或附加多行文本,必须在要插入或附加的每行新文本末尾使用反斜线(\): $ sed ‘1i\ > This is an inserted line.\ > This is another inserted line. > ’ data6.txt This is an inserted line. This is another inserted line. This is line number 1. This is line number 2. This is the 3rd line. This is the 4th line. $ 指定的两行都会被添加到数据流中。

From #

Linux命令行与shell脚本编程大全