# sed命令工作原理及命令备忘

sed是一个非交互式的流编辑器（stream editor）。所谓非交互式，是指使用sed只能在命令行下输入编辑命令来编辑文本，然后在屏幕上查看输出；而所谓流编辑器，是指sed每次只从文件（或输入）读入一行，然后对该行进行指定的处理，并将结果输出到屏幕（除非取消了屏幕输出又没有显式地使用打印命令），接着读入下一行。整个文件像流水一样被逐行处理然后逐行输出。

# 工作原理

## 核心逻辑

sed一次处理一行内容。处理时，把当前处理的行存储在临时缓冲区中，称为“模式空间”（pattern space），接着用sed命令处理缓冲区(pattern space)中的内容，处理完成后，把缓冲区(pattern space)的内容送往屏幕。接着清空缓冲区(pattern space)，处理下一行，这样不断重复，直到文件末尾。

sed里有两个空间：pattern space与hold space。

pattern space（模式空间）相当于车间sed把流内容在这里处理；

hold space（保留空间）相当于仓库，加工的半成品在这里临时储存（当然加工完的成品也在这里存储）。

sed处理每一行的逻辑：

1. 先读入一行，去掉尾部换行符，存入pattern space，执行编辑命令。

2. 处理完毕，除非加了-n参数，把现在的pattern space打印出来，在后边打印曾去掉的换行符。

3. 把pattern space内容给hold space，把pattern space置空。

4. 接着读下一行，处理下一行。

## 命令组织形式

sed最重要的命令组织形式可以概括为*** address[,address]{cmd} ***

### address

address可以是一个数字，也可以是一个模式，你可以通过逗号要分隔两个address 表示两个address的区间

man手册上对address的理解比较全面

1234567891011121314151617181920212223242526272829303132333435

Addresses Sed commands can be given with no addresses, in which case the command will be executed for all input lines; with one address, in which case the command will only be executed for input lines which match that address; or with two addresses, in which case the command will be executed for all input lines which match the inclusive range of lines starting from the first address and continuing to the second address. Three things to note about address ranges: the syntax is addr1,addr2 (i.e., the addresses are separated by a comma); the line which addr1 matched will always be accepted, even if addr2 selects an earlier line; and if addr2 is a regexp, it will not be tested against the line that addr1 matched. After the address (or address-range), and before the command, a ! may be inserted, which specifies that the command shall only be executed if the address (or address-range) does not match. The following address types are supported: number Match only the specified line number (which increments cumulatively across files, unless the -s option is specified on the command line). first~step Match every step'th line starting with line first. For example, sed -n 1~2p'' will print all the odd-numbered lines in the input stream, and the address 2~5 will match every fifth line, starting with the second. first can be zero; in this case, sed operates as if it were equal to step. (This is an extension.) \$ Match the last line. /regexp/ Match lines matching the regular expression regexp. \cregexpc Match lines matching the regular expression regexp. The c may be any character. GNU sed also supports some special 2-address forms: 0,addr2 Start out in "matched first address" state, until addr2 is found. This is similar to 1,addr2, except that if addr2 matches the very first line of input the 0,addr2 form will be at the end of its range, whereas the 1,addr2 form will still be at the beginning of its range. This works only when addr2 is a regular expression. addr1,+N Will match addr1 and the N lines following addr1. addr1,~N Will match addr1 and the lines following addr1 until the next line whose input line number is a multiple of N.

### cmd

##### 不可接受address的命令

1

} The closing bracket of a { } block.

##### 可接受零个或一个address的命令

123456789101112131415

= Print the current line number.a \text Append text, which has each embedded newline preceded by a backslash.i \text Insert text, which has each embedded newline preceded by a backslash.r filename Append text read from filename.R filename Append a line read from filename. Each invocation of the command reads a line from the file. This is a GNU extension.

##### 可接受address范围的命令

1234567891011121314151617181920212223242526272829303132333435

{ Begin a block of commands (end with a }).c \text Replace the selected lines with text, which has each embedded newline preceded by a backslash.d Delete pattern space. Start next cycle.D If pattern space contains no newline, start a normal new cycle as if the d command was issued. Otherwise, delete text in the pattern space up to the first newline, and restart cycle with the resul- tant pattern space, without reading a new line of input.h H Copy/append pattern space to hold space.g G Copy/append hold space to pattern space.n N Read/append the next line of input into the pattern space.p Print the current pattern space.P Print up to the first embedded newline of the current pattern space.s/regexp/replacement/ Attempt to match regexp against the pattern space. If successful, replace that portion matched with replacement. The replacement may contain the special character & to refer to that portion of the pattern space which matched, and the special escapes \1 through \9 to refer to the corresponding matching sub-expressions in the regexp.w filename Write the current pattern space to filename.W filename Write the first line of the current pattern space to filename. This is a GNU extension.x Exchange the contents of the hold and pattern spaces.y/source/dest/ Transliterate the characters in the pattern space which appear in source to the corresponding character in dest.

# PS

MAC OSX里记得需要使用brew install gnu-sed安装GNU版的sed，然后使用gsed， 自带的BSD版本sed功能实在弱了点。

188 篇文章40 人订阅

0 条评论

## 相关文章

28370

23070

18750

### Google-LevelDB简介

LevelDB简介 LevelDB一句话描述 LevelDB是google开发的，一个速度非常块的KV存储库（storage library），它支持字符串的k...

52550

19750

15410

### PDF.NET（PWMIS数据开发框架）之SQL-MAP目标和规范

SQL-MAP的目标： 集中管理SQL语句，所有SQL语句放在专门的配置文件中进行管理； 通过替换SQL配置文件，达到平滑切换数据库到另外一个数据库，比如从O...

27780

29490

### ------------数据库的加锁操作（上）

从事一个项目，需要考虑数据的安全性，之前对于数据库这部分的数据操作学习的比较零散，由于手头的项目，于是系统的 学习了下数据库操作加锁的知识： --...

563100

20450