插入和添加文本

我们可以使用以下标志插入或者添加文本行:

  • (i) 标志。
  • (a) 标志。

在指定行前面添加文本

$ echo "Another test" | sed 'i\First test '

在指定行后面添加文本

$ echo "Another test" | sed 'a\First test '

在中间添加文本

$ sed '2i\This is the inserted line.' myfile
$ sed '2a\This is the appended line.' myfile

从文件中读取数据

我们可以使用 (r) 标志从文件中读取数据。

$ cat newfile
$ sed '3r newfile' myfile

这是使用文本模式:

$ sed '/test/r newfile' myfile

在命令行中使用多个 sed Linux 命令

要运行多个 sed 命令,我们可以使用 -e 选项,如下所示:

$ sed -e 's/This/That/; s/test/another test/' ./myfile

我们必须用不带任何空格的分号分隔 sed 命令。

此外,我们可以使用单引号来分隔这样的命令:

$ sed -e '
> s/This/That/
> s/test/another test/' myfile

替换字符

在/etc/passwd文件中搜索bash shell并用csh shell替换

$ sed 's/\/bin\/bash/\/bin\/csh/' /etc/passwd

要转义很多,看起来很乱。

我们可以使用感叹号 (!) 作为字符串分隔符,如下所示:

$ sed 's!/bin/bash!/bin/csh!' /etc/passwd

从文件中读取命令

我们可以将 sed 命令保存在文件中,并通过使用 -f 选项指定文件来使用它们。

$ cat mycommands
s/This/That/
s/test/another test/
$ sed -f mycommands myfile

限制 sed

sed 命令处理你的整个文件。
但是,我们可以限制 sed 命令处理特定行;有两种方法:

  • 指定行范围
  • 匹配特定行的模式。

我们可以键入一个数字以将其限制为特定行,
我们只修改了第二行:

$ sed '2s/test/another test/' myfile

只修改2到5行

$ sed '2,5s/test/another test/' myfile

第2行到文件末尾:

$ sed '2,$s/test/another test/' myfile

打印行号

我们可以使用 (=) 符号打印行号,如下所示:

$ sed '=' myfile

但是,通过将 -n 与等号结合使用,sed 命令会显示包含匹配项的行号。

$ sed -n '/test/=' myfile

修改行

要修改特定行,我们可以使用 (c) 标志,如下所示:

$ sed '3c\This is a modified line.' myfile

我们可以使用正则表达式模式,所有与该模式匹配的行都将被修改。

$ sed '/This is/c Line updated.' myfile

变换字符

变换标志 (y) 对这样的字符起作用:

$ sed 'y/123/567/' myfile

语法

$ sed options file

我们不仅限于使用 sed 来操作文件;你可以像这样直接将它应用到 STDIN:

$ echo "Welcome to onitroad page" | sed 's/page/website/'

s 命令用第二个文本模式替换第一个文本。
在本例中,我们将字符串“website”替换为“page”一词。

我们也可以使用 sed Linux 命令来操作文件。

让我们创建一个示例文件:

$ sed 's/test/another test/' ./myfile

结果即时打印到屏幕上。

Sed Linux 命令不会更新数据。
它只将更改后的文本发送到 STDOUT。

删除行

要使用 sed 删除行,我们可以使用 delete (d) 标志。

删除标志从流中删除文本,而不是原始文件。

删除第2行

$ sed '2d' myfile

删除2-3行

$ sed '2,3d' myfile

删除第3行到末尾的行

$ sed '3,$d' myfile
Linux sed 命令示例

sed 命令是一个非交互式文本编辑器。

sed Linux 命令根据我们提供的规则编辑数据。

使用sed进行替换

看下面的例子:

$ cat myfile
$ sed 's/test/another test/' myfile

将test替换为another test

要替换所有出现的模式,请使用以下替换标志之一。

我们可以这样写标志:

s/pattern/replacement/flags

有四种类型的替换:

  • g、替换所有出现的。
  • 一个数字,即要替换的新文本的出现次数。
  • p、打印原始内容。
  • w file:表示将结果写入文件。

我们可以通过指定应替换的出现次数来限制替换,如下所示:

$ sed 's/test/another test/2' myfile

g 标志表示全局,这意味着所有出现的全局替换:

$ sed 's/test/another test/g' myfile

p 标志打印包含模式匹配的每一行,我们可以使用 -n 选项仅打印修改后的行。

$ cat myfile
$ sed -n 's/test/another test/p' myfile

w 标志将输出保存到指定的文件:

$ sed 's/test/another test/w output' myfile

将匹配的行保存到输出文件中。

日期:2020-07-15 11:16:45 来源:oir作者:oir