sed笔记(2)
[addr]X[options]
X是单字母的sed命令
addr是可选的,行地址
如果指定addr,命令X仅执行在这些匹配的行上
addr可是一个行号,也可以是正则表达式,或者行范围
额外的options用于特定的sed命令
命令之间用;或者新行分隔
多script可以用-e或者-f选择指定
因为语法,a,c,i命令不能后面跟;需要使用newline
或者将他们放到script文件中
sed的命令

pattern space于hold space
sed维护两份数据缓存:pattern space和备用的hold space
初始都为空
除非是特殊命令(像D),否则两个cycle间,pattern space被删除
这个时候就需要hold space保持数据跨cycle
h: pattern --> hold
g: hold --> pattern
x: hold <-->pattern
H, G是多行模式中对应的命令,注意他们是append,不是replace
多行模式
形成多行的是命令
$ seq 6 | sed -n 'N;l;D'
1\n2$
2\n3$
3\n4$
4\n5$
5\n6$
D
deletes line from the pattern space until the first newline, and restarts the cycle.
G
appends line from the hold space to the pattern space, with a newline before it.
H
appends line from the pattern space to the hold space, with a newline before it.
N
appends line from the input file to the pattern space.
P
prints line from the pattern space until the first newline.
关于label
label,通常是一个字母
b label 无条件跳转到label
t label
branch conditionally (that is: jump to a label) only if a s/// command has succeeded since the last input line was read or another conditional branch was taken.
T label
similar but opposite to the t command: branch only if there has been no successful substitutions since the last input line was read.
开始下一轮cycle的命令
b,t,T的label如果省略,开始下一轮cycle
d:删除pattern space,立即开始下一轮cycle
D: 删除到下一个newline,重新对剩余的pattern space做cycle,并不从input中读取新的行
如果没有newline,行为同d
s命令
语法:
s/regexp/replacement/flags
replacement中可以有\n, n为1-9,表示正则表达式的第n个括号
非转义的&表示pattern spac中整个匹配部分
这个的/可以统一被其他字符替代, 如果s!abc!cba!g
replace里的下列字符含义
\L
Turn the replacement to lowercase until a \U or \E is found,
\l
Turn the next character to lowercase,
\U
Turn the replacement to uppercase until a \L or \E is found,
\u
Turn the next character to uppercase,
\E
Stop case conversion started by \L or \U.
关于flag:
g:替换所有的的匹配
number:替换第number个匹配
p:打印
w filename:替换发生后,将pattern space的内容写入文件
e:替换发生后,将pattern space的内容作为命令执行,将pattern space的内容替换为命令执行的输出
I与i 正则表达式忽略大小写
M与m 正则表达式支持多行
浙公网安备 33010602011771号