Linux基本命令之sed

语法格式
sed [options] [sed-commands] [input-file]
选项 [sed命令] [输入文件]

说明
1、sed-commands既可以是单个sed命令,也可以是sed命令组合
2、input-file(输入文件)是可选项,sed还能够从标准输入,如:管道获取输入

命令流程
Linux基本命令之sed

sed模式空间:sed软件内部的一个临时缓存,用于存放读取到的内容。
Linux基本命令之sed

例子:
1、使用文本
Linux基本命令之sed
2、增删改查

2.1增
a:追加文本到指定行后
i:插入文本到指定行前

2.1.1单行增加
Linux基本命令之sed
注:这是改变输出,而文本内容不会有任何变化,要想改变内容要加-i参数
Linux基本命令之sed

2.1.2多行增加
Linux基本命令之sed
记住这里一定要用单引号‘’
Linux基本命令之sed
Linux基本命令之sed
2.2删
d:删除指定的行
Linux基本命令之sed
案例:打印文件内容不包含abc
Linux基本命令之sed

2.3改
2.3.1按行替换
c:用新行替换旧行
Linux基本命令之sed

2.3.2文本替换

  1. s:单独使用将每一行中第一次匹配的字符串进行替换
  2. g:每一行进行全部替换
  3. i:修改文件内容
    Linux基本命令之sed
    说明:#是定界符,,定界符可以是任意符号。当替换内容包含定界符的时候,需转义。建议使用#。

案例:指定修改配置文件
Linux基本命令之sed

2.3.3变量替换
Linux基本命令之sedLinux基本命令之sed

2.3.4分组替换\( \)和\1的使用说明
Linux基本命令之sed
Linux基本命令之sed
Linux基本命令之sed

案例:系统开机启动项优化
Linux基本命令之sed

2.3.5特殊符号&代表被替换的内容
Linux基本命令之sed

案例:批量重命名文件
Linux基本命令之sed
Linux基本命令之sed

2.4查
p:输出指定内容,当默认会输出2次(为什么是2次,因为sed命令会默认读取一行,输出一行,然后遇到p参数,再读取一行,输出一行)匹配的结果,因此使用n取消默认输出

2.4.1按行查询
Linux基本命令之sed
2.4.2按字符船查询
Linux基本命令之sed
2.4.3混合查询
Linux基本命令之sed
Linux基本命令之sed
特殊情况,前两行没有匹配到g,就向后匹配,如果匹配到g就打印此行

猜你喜欢

转载自blog.51cto.com/12489067/2325017