语法
语法:
sed [选项] '模式动作' 文件...
选项参数
参数 | 说明 |
---|---|
-n | 静默输出,输出匹配到的行及处理结果 |
-i | 直接将修改结果写入文件,不用-i,sed修改的是内存数据 |
-e | 多次编辑执行动作:-e ‘动作1’ -e ‘动作2’ 等效于 ‘动作1;动作2’ |
-r | 支持正则拓展 |
常用内置动作命令参数
动作参数 | 说明 |
---|---|
a | 新增, a 的后面可以接字串,而这些字串会在新的一行出现(目前的下一行) |
d | 删除,后面通常不接任何东西 |
i | 插入, i 的后面可以接字串,而这些字串会在新的一行出现(目前的上一行) |
p | 打印,亦即将某个选择的数据印出。通常 p 会与参数 sed -n 一起运行 |
s/正则/替换内容/g | 例如 1,20s/old/new/g 就是将1到20行的old替换为new |
sed -n 输出处理过的匹配数据
匹配范围
范围 | 解释 |
---|---|
空地址 | 全文处理 |
但地址 | 指定文件某一行 |
/pattern/ | 被模式匹配到的每一行 |
范围区间 | 10,29 十到二十行 , 10,+5第10行向下5行 , /pattern1/,/pattern2/ |
步长 | 1~2 , 表示1、3、5、7、9行,2~2两个步长,表示2、4、6、8、10 、偶数行; |
sed处理数据在内存中,-n决定处理匹配数据
样本
HELLO LINUX! Linux is a free unix-type opterating system. This is a linux testfile! Linux test Google Taobao Runoob Tesetfile Wiki
输出
输出(print)文件第二三行数据:
sed -n '2,3p' sedSrc.txt
默认输出全部(匹配和不匹配数据)
[e3base01@localhost str-parse]$ sed '2,3p' sedSrc.txt
HELLO LINUX!
Linux is a free unix-type opterating system.
Linux is a free unix-type opterating system.
This is a linux testfile!
This is a linux testfile!
Linux test
Taobao
Runoob
Tesetfile
Wiki
加-n输出匹配处理数据
@localhost str-parse]$ sed -n '2,3p' sedSrc.txt
Linux is a free unix-type opterating system.
This is a linux testfile!
过滤筛选字符串数据
sed -n '/Linux/p' sedSrc.txt
Linux is a free unix-type opterating system.
Linux test
增加
在某一行上面插入内容
sed '2i insert a new Line' sedSrc.txt
HELLO LINUX!
insert a new Line
Linux is a free unix-type opterating system.
… …
在每一行下面插入新内容
sed 'a -----------------------' sedSrc.txt
HELLO LINUX!
-----------------------
Linux is a free unix-type opterating system.
-----------------------
This is a linux testfile!
-----------------------
Linux test
-----------------------
添加多行
文本添加换行符
sed 'a Line one \n Line two \n Line three' sedSrc.txt
HELLO LINUX!
Line one
Line two
Line three
Linux is a free unix-type opterating system.
修改(替换)
s内置符配合g,代表全局替换
//替换谷歌为百度
sed "s/Google/Baidu/g" sedSrc.txt
//多次替换
sed -e "s/Google/Baidu/g" -e "s/Taobao/TianMao/g" sedSrc.txt
删除
//删除匹配Linux的行
sed '/Linux/d' sedSrc.txt
//删除2到3行
sed '2,3d' sedSrc.txt
//删除2到结尾行数
sed '2,$d' sedSrc.txt
sed配合正则表达式
略