Linux命令——Sed
Sed牛逼!
语法
sed [-hnV][-e<script>][-f<script文件>][文本文件]
- -h:显示帮助信息
- -n:仅显示脚本处理后的结果
- -V:显示版本信息
- -e:以指定的script处理文本文件
- -f:以指定的script文件来处理文本文件
- -i:直接修改文件内容(-i.bak将会创建原文件的备份)
命令
- a\:插入,后加字符串,会出现在下一行
- i\:插入,后加字符串,出现在目标上一行
- c\:替换,将选定的行修改为新的文本
- s:替换,搭配正则表达式使用
- d:删除选择的行
- p:打印,选择数据并打印
script
当script中的正则表达式含有复杂表达式影响解析时,需使用/来定界
插入(增)
sed '/Search_String/a(/i)\Add_String' file
- Search_String:需要查找行的正则表达式
- a:当前行后插入
- i:当前行前插入
- Add_String:需要插入的文本
示例
sed '/^test/a\this is a test line' file
,将this is a test line添加到以test开头的行后面sed '2a\this is a test line' file
,在文件的第二行后插入sed '5i\this is a test line' file
,在文件的第五行前插入
删除(删)
sed '/Search_String/d' file
- d:删除
- Search_String:正则表达式,匹配特定行`
- 当删除特定行时,直接使用
sed '2d' file
即可示例:
- 删除空白行:
sed '/^$/d' file
- 删除第二行到末尾行:
sed '2,$d' file
- 删除文件中所有开头是test的行:
sed '/^test/'d file
- 删除第二行:
sed '2d' file
替换(改)
sed 's/Search_String/Replacement_String/Ng' Input_File
- s:替换
- Search_String:搜索的字符串或者正则表达式
- Replacement_String:替换的字符串
- N:从第N处开始匹配
- g:全局替换标志,替换每一行的全部匹配
- /:定界符re
参考链接与其他示例
本文标题:Linux命令——Sed
文章作者:Raincorn
发布时间:2020-07-18
最后更新:2020-07-28
原始链接:https://blog.raincorn.top/2020/07/18/Linux_Command_Sed/
版权声明:本文采用知识共享署名-非商业性使用 4.0 国际许可协议进行许可