Skip to content

sed(Stream editor)

webdes
blog

工作模式

第一种:stdout | sed [option] "pattern command"

第二种:sed [option] "pattern command" file

选项

选项描述
-n只打印模式匹配行,不加-n参数则所有行都打印
-e直接在命令行进行sed编辑,用于多个匹配,or关系,如:-e /patter1/ -e /patter2/
-f编辑命令保存于文件,指定文件执行
-r支持正则
-i直接修改文件内容

匹配模式

序号模式示例描述
1LineNumbersed -n "17p" file指定行号
2startLine, endLinesed -n "10, 20p" file起始到结束行
3StartLine ,+nsed -n "10, +5p" file指定起始行号,然后后面n行
4/pattern1/sed -n "/^root/p" file正则匹配行
5/pattern1/,/pattern1/sed -n "/pattern1/,/pattern2/p" file从匹配的行到匹配的行
6LineNumber,/pattern1/sed -n "10,/^hdfs/p" file从指定行号匹配到匹配行
7/pattern1/,LineNumbersed -n "/^hdfs/,10p" file从匹配行匹配到指定行号

编辑命令

动作命令示例描述
打印psed -n "/pattern/p" file打印匹配内容
删除dsed -i "/pattern/d" fileDelete match content
增加ased -i "/pattern/a content" fileadd after the match line
增加ised -i "/pattern/i content" fileadd before the match line
增加rsed -i "/pattern/r file1" fileAdd the the content of file1 after the match line
增加wsed -i "/pattern/w file1" filewrite the match line to the file1

修改命令

s/pattern/string/ing n表示替换第二个匹配字符串,ng表示从第二个开始替换所有匹配, 表示忽略大小写

显示行号

sed -n "/pattern/=" file

删除命令

sed -i "/[:blank:]*#/d" file 删除以#开头但是#前边有空格的注释行