Linux 中的sed工具 字符串的替换,删除,插入等功能

sed工具

sed工具是Linux中的一个很好用的工具,经常被用来处理文本,进行字符串的替换,删除,插入等操作。

参数说明
-n使用安静模式,在一般的sed用法中,所有来自STDIN的数据一般都会被列出到屏幕上。但如果加上-n参数了以后,则只有经过处理的内容才会被打印出来
-e直接在命令行模式上进行sed的操作
-f直接将sed的动作卸载一个文件内,-f filename则可以执行filename内的sed动作
-r支持扩展正则表达式(默认是基础正则表示式语法)
-i直接修改读取的文件内容,而不是由屏幕输出,例如直接修改文件

动作说明

一般语法, 注意已下的内容务必在’'中使用
[n1[,n2]] function
n1, n2 不一定会存在,看具体的执行内容

function说明(具体用法看后面的示例)
a新增,a的后面可以接字符串,而这些字符串会出现在新的一行(指定的下一行)
c替换,c的后面可以接字符串,这些字符串可以替换n1, n2之间的行
d删除,因为是删除,所以d后面通常不接任何参数
i插入,i的后面可以接字符串,而这些字符串会在新的一行出现(指定的上一行)
p打印,也就是将选择的数据打印出来,通常p会与参数-n一起使用
s替换,可以直接进行替换的工作,通常这个s的动作可以搭配正则表达式一起使用,具体用法看后面的示例吧

示例

以下的示例内容是基于假定存在一个文件Example.txt的
Example的内容如下

  1. This is the first line.
  2. This is the second line.
  3. This is the third line.
  4. This is the fourth line.
  5. This is the fifth line.

删除(d)

$ nl Example.txt | sed '2,4d'
1. This is first line.
5. This is fifth line.

添加(a)

$ nl Example.txt | sed '2a new line'
1. This is first line.
2. This is second line.
new line
3. This is third line.
4. This is fourth line.
5. This is fifth line.

文本替换(s)

语法:sed ‘s/要被替换的字符串/新的字符串/g’

$ nl Example.txt | sed 's/first/1/g'
1. This is 1 line.
2. This is second line.
3. This is third line.
4. This is fourth line.
5. This is fifth line.

替换行(c)

$ nl Example.txx | sed '2,4c new line'
1. This is first line.
new line
5. This is fifth line.

打印(p)

$ nl Example.txt | sed -n '2,4p'
2. This is second line.
3. This is third line.
4. This is fourth line.

直接修改文件

$ sed -i 's/first/1/g' Example.txt
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值