sed
简介:sed 是 stream editor 的缩写,中文称之为“流编辑器”,命令是面向“行”进行处理的,每一次处理一行内容sed 会把要处理的行存储在缓冲区中,接着用 sed 命令处理缓冲区中的内容,处理完成后,把缓冲区的内容送往屏幕。接着处理下一行,这样不断重复,直到文件末尾。这个缓冲区被称为“模式空间”(pattern space)
使用方式:sed [options] [script] [file_name]
sed很多人都说很难学习,因为分门别类就去掌握,我们主要从以下三个方面去掌握,明白下面两个概念,就能清楚掌握Sed
- options 其实说,你们操作打印到shell中,还是写入文本中
- scprit 要执行的操作,新增、删除、替换,但是首先要明确执行的范围就是scope,特殊注意 替换 操作,在行操作的匹配范围就OK
options 执行的动作
options | desc |
---|
空 | 就默认-e ,执行后面script脚本,并将结果输出到标准输出,默认shell |
-n | 取消默认空间,及不打印到标准输出 |
-i[扩展名], --in-place[=扩展名] | 直接修改文件(如果指定扩展名就备份文件) |
scprit 有三个scope、action、line_scope,
- 一般以包含在引号中,单双引号都可以,‘scope s/target_txt/replace_txt/line_scope’ OR “scope s/target_txt/replace_txt/line_scope”
- 注意一点,scprit中的分隔符可以使用"“、”/“、”#",当txt有分隔符时,可以替换使用
scope 表示操作范围,文本中行数
scope | desc |
---|
空 | 表示整个文件 |
n | 表示第n行 |
{n,m} | 表示第n到第m行,闭区间 |
{n,m}! | 标识在非n到第m行 |
action 表示匹配后动作
action | desc | demo |
---|
a | 在scope范围内,每一行下面插入目标文档 | sed ‘scope a target_txt’ filename |
i | 在scope范围内,每一行上面插入目标文档 | sed ‘scope i target_txt’ filename |
c | 在scope范围内的所有行替换为目标文本 | sed ‘scope c/target_txt’ filename |
d | 删除scope范围内行 | sed ‘scoped’ filename |
p | 打印scope范围内行,一般与-n同时使用 | sed -n ‘scope p’ filename |
s | 在scope范围内,替换target_txt为replace_txt | sed ‘scope s/target_txt/replace_txt/line_scope’ filename |
r inputfile | 将inputfile中内容追加scope范围内所有filename中行后 | sed ‘scope r inputfile’ filename |
w outfie | 将filename中scope范围内所有内容,覆盖写入到outfie | sed ‘scope w outfile’ filename |
line_scope 标志位,标识搜索范围
line_scope | desc |
---|
空 | 替换行中第一个匹配目标 |
g | 替换行中所有的匹配目标 |
p | 打印匹配行 |