sed参考文档
语法:
sed [-hnV][-e<script>][-f<script文件>][文本文件]
-e<script>
或--expression=<script>
以选项中指定的script来处理输入的文本文件。如果不加-e ,那么sed后面的命令要用'命令....'
单引号包括起来- -f<script文件>或–file=<script文件> 以选项中指定的script文件来处理输入的文本文件。
- -h或–help 显示帮助。
- -n或–quiet或–silent 仅显示script处理后的结果。
- -V或–version 显示版本信息。
动作说明:
- a :新增, a 的后面可以接字串,而这些字串会出现在新的一行(当前行的下一行)
- c :取代, c 的后面可以接字串,这些字串可以取代 n1,n2 之间的行
- d :删除,因为是删除,所以 d 后面通常不接任何参数;
- i :插入, i 的后面可以接字串,而这些字串会在新的一行出现(目前的上一行);
- p :打印,将某个选择的数据印出。通常 p 会与参数 sed -n 一起运行
- s :取代,通常这个 s 的动作可以搭配正规表示法
命令案例
-
-e 注意,这里所有的增删改命令都只是修改输出内容,而不修改原本文件内容
#这里的$代表最后一行。 #添加 a sed -e 4a\newLine testfile # 在文件第4行添加"newLine"内容 nl testfile | sed '2a drink tea' #在第二行后(即加在第三行) 加上drink tea nl testfile | sed '2i drink tea' #在第二行前插入drink tea # 添加多行用 \ 分隔 nl testfile | sed '2a drink tea \ 第二行内容' #在第二行后(即加在第三行) 加上drink tea 以及第二行内容, #删除 d nl testfile | sed '2,5d' # 删除testfile文件的2~5行内容 nl testfile | sed '3,$d' # 要删除第 3 到最后一行,$代表最后一行 nl testfile | sed '/oo/d' # 删除带有oo的行 # 替换 c nl testfile | sed '2,5c replace 2-5 number' # 将2~5行替换成 replace 2-5 number # 正则搜索替换 s,搜索字符串的 sed 's/要被取代的字串/新的字串/g' #全局替换字符串,g代表全局, sed 's/要被取代的字串/新的字串/' #只替换第一处搜索到的内容
-
-n 列出
nl testfile | sed -n '5,7p' #输出5~7行 nl testfile | sed -n '/oo/p' #搜索出带有oo的行 nl testfile | sed -n '/oo/{s/oo/kk/;p;q}' #搜索带oo的行,并执行{}里面的命令,
-
-i 修改
sed -i 's/oo/kk/g' testfile # 修改testfile,全局替换oo为kk sed -i 's/oo/kk/g' ./test* # 修改test开头的文件,
-
多个命令编辑
#一条 sed 命令,删除 testfile 第三行到末尾的数据,并把 HELLO 替换为 RUNOOB nl testfile | sed -e '3,$d' -e 's/HELLO/RUNOOB/'