多重命令
实例:
修改words文本把lcc修改成lichengcheng,同时把hate修改成love。
sed 's/lcc/lichengcheng/; s/hate/love/' words
sed -e 's/lcc/lichengcheng/' -e 's/hate/love/' words
分行
sed '
quote> s/lcc/lichengcheng/
quote> s/hate/love/' words
脚本文件
语法:
sed -f <scriptfile脚本文件> <file待处理文件名称
>
编写sed脚本:
vim sed-script
s/lcc/lichengcheng/
s/hate/love/
bash脚本模式:
vim replace.sed
#!/bin/sed -f
s/lcc/lichengcheng/
s/hate/love/
:wq
sudo chmod +x replace.sed
./replace.sed words
寻址
新建文件xunzhi:
sudo vim xunzhi
a b
b
c
d b
e
f
:wq
实例1:
把文件中的b字符替换成new:
nl xunzhi | sed 's/b/new'
实例2:
把文件中a所在行的b替换成new:
nl xunzhi | sed '/a/s/b/new/'
实例3:
删除最后一行:
nl xunzhi | sed '$d'
实例4:
删除空行:
cat xunzhi | sed '/^$/d'
实例5:
删除第三行到最后一行:
nl xunzhi | sed '3,$d'
分组
修改xunzhi文件的内容:
sudo vim xunzhi
a b hello world
b world
c b d hello world
d b world good
e hello
f
实例1:
把第一行的world改成lcc,再把第五行的world替换成linux
vim fenzu
/b/{
/hello/s/world/lcc/
/d /s/world/linux/
}
缓冲空间
sed的两个缓冲空间:
- pattern space:模式空间,用于存放读取到的内容
- hold space:保持空间,用于暂存存储模式空间传过来的内容
sed允许匹配扩展到多行,包含3个多行命令
- N:追加下一行
- D:删除多行模式空间的第一行
- P:打印多行模式空间中的第一行
新建文本:
vim zhuijia
Permission is granted to copy, distribute and/or modify
that document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation;
with no Invariant Sections, ## 标题
no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled “GNU Free Documentation License
追加下一行:
实例1:把zhuijia文本中的modify that document替换成modify this document.
vim sedn
N
s/modify\nthat/modify this/
:wq
sed -f sedn zhuijia
保持空间:
常用命令:
- Hold:缩写h或H,将模式空间的内容复制或追加到保持空间
- Get:缩写g或G,将保持空间内容复制或追加到模式空间
- Exchange:缩写x,减缓保持空间和模式空间的内容
实例:
新建一个reverse.sed的脚本:
#!/bin/sed -nf
1! G
$ p
h
添加执行权限:
sudo chmod +x reverse.sed
./reverse.sed words