欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

sed编辑器基础——s命令

程序员文章站 2022-03-04 17:54:18
...

sed编辑器简介

sed编辑器是流编辑器(stream editor),sed编辑器不会修改原文件中的内容。

sed编辑器操作步骤

  1. 一次从输入中读取一行数据。
  2. 根据所提供的编辑器命令匹配数据。
  3. 按照命令修改流中的数据。
  4. 将新的数据输出到STDOUT。

sed编辑器基础

sed的s命令

s命令的格式:
s/pattern/replacement/flags
s命令会用斜线间指定的第二个文本字符串来替换第一个文本字符串模式。

-> echo "This is a test" | sed 's/test/big test/'
This is a big test 

s命令也可以编辑整个文件,准备一个data1.txt文件

-> cat data1.txt
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy monkey.
The quick brown fox jumps over the lazy cat.
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
-> sed 's/dog/cat/' data1.txt
The quick brown fox jumps over the lazy cat.
The quick brown fox jumps over the lazy cat.
The quick brown fox jumps over the lazy monkey.
The quick brown fox jumps over the lazy cat.
The quick brown fox jumps over the lazy cat.
The quick brown fox jumps over the lazy cat.

从结果中可以看到所有的dog->cat了。

在命令行中使用多个编辑器命令

-> sed -e 's/dog/cat/;s/monkey/dog/' data1.txt
The quick brown fox jumps over the lazy cat.
The quick brown fox jumps over the lazy cat.
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy cat.
The quick brown fox jumps over the lazy cat.
The quick brown fox jumps over the lazy cat.

从文件中读取编辑器命令

准备的脚本文件如下:

-> cat script1.sed
s/brown/green/
s/fox/elephant/
s/dog/cat/
-> sed -f script1.sed data1.txt
The quick green elephant jumps over the lazy cat.
The quick green elephant jumps over the lazy cat.
The quick green elephant jumps over the lazy monkey.
The quick green elephant jumps over the lazy cat.
The quick green elephant jumps over the lazy cat.
The quick green elephant jumps over the lazy cat.

sed的次提示符

-> sed -e '
> s/brown/green/
> s/fox/elephant/
> s/dog/cat/' data1.txt
The quick green fox jumps over the lazy cat.
The quick green fox jumps over the lazy cat.
The quick green fox jumps over the lazy monkey.
The quick green fox jumps over the lazy cat.
The quick green fox jumps over the lazy cat.
The quick green fox jumps over the lazy cat.

只要输入第一个单引号标示出sed程序脚本的起始,终端会继续提示你输入更多命令,直到输入了标示出结束的单引号。

相关标签: sed