Linux学习---sed命令

先准备一个1.txt,里面的内容如下:

[root@localhost] ~/w/a/sed$ cat 1.txt
1.txt
1.xtt
7.txt
888.txt
test
test01
test02
test666

使用sed命令时,最好先备份测试文件,以免文件内容缺失

 

一、增加文本内容

1)使用“a”追加文本到指定行后面,但只是写入内存,不修改真正的文本。(也就是说仅仅是打印到屏幕,文本内容并没有修改)

将“222222”追加到第二行后面,输入:sed "2a 222222" 1.txt

[root@localhost] ~/w/a/sed$ sed "2a 222222" 1.txt
1.txt
1.xtt
222222
7.txt
888.txt
test
test01
test02
test666

使用cat命令进行查看文本内容,可以发现“222222”没有真正追加到文本

[root@localhost] ~/w/a/sed$ sed "2a 222222" 1.txt
1.txt
1.xtt
222222
7.txt
888.txt
test
test01
test02
test666
[root@localhost] ~/w/a/sed$ cat 1.txt
1.txt
1.xtt
7.txt
888.txt
test
test01
test02
test666

 

2)使用“i”插入文本到指定行前面,但只是写入内存,不修改真正的文本。(也就是说仅仅是打印到屏幕,文本内容并没有修改)

输入:sed "2i 222222" 1.txt

[root@localhost] ~/w/a/sed$ sed "2i 222222" 1.txt
1.txt
222222
1.xtt
7.txt
888.txt
test
test01
test02
test666

使用cat命令进行查看,可以发现“222222”没有真正插入到文本

[root@localhost] ~/w/a/sed$ sed "2i 222222" 1.txt
1.txt
222222
1.xtt
7.txt
888.txt
test
test01
test02
test666
[root@localhost] ~/w/a/sed$ cat 1.txt
1.txt
1.xtt
7.txt
888.txt
test
test01
test02
test666

3)要想真正实现添加文本内容,需要在sed后面加上“-i”

把“222222”插入到第二行前,输入:sed -i "2i 222222" 1.txt

[root@localhost] ~/w/a/sed$ sed -i "2i 222222" 1.txt
[root@localhost] ~/w/a/sed$ cat 1.txt
1.txt
222222
1.xtt
7.txt
888.txt
test
test01
test02
test666
[root@lo

 

二、删除文本内容

1)删除单行文本内容

删除刚才添加的字符串“222222”那一行,输入:sed -i "2d" 1.txt

[root@localhost] ~/w/a/sed$ sed -i "2d" 1.txt
[root@localhost] ~/w/a/sed$ cat 1.txt
1.txt
1.xtt
7.txt
888.txt
test
test01
test02
test666

 

2)删除多行文本内容

比如我想删除1到3行的文本内容,输入:sed -i "1,3d" 1.txt

[root@localhost] ~/w/a/sed$ sed -i "1,3d" 1.txt
[root@localhost] ~/w/a/sed$ cat 1.txt
888.txt
test
test01
test02
test666

 

3)利用正则表达式删除指定文本内容

格式为:sed -i “/正则表达式/d”【文件名】

比如我想删除1.txt里的“888.txt”这一行,只需正则包含888即可,输入:sed -i “/888/d” 1.txt

[root@localhost] ~/w/a/sed$ sed -i "/888/d" 1.txt
[root@localhost] ~/w/a/sed$ cat 1.txt
test
test01
test02
test666

 

三、文本替换

格式为:sed -i “s#目标内容#替换内容#g”【文件名】

目标内容可以用正则表达式,替换内容不能使用正则表达式,g为全局替换,用不到可以省略。

将1.txt的“test”全部替换为“node”,

输入:sed -i "s#test#node#g" 1.txt

[root@localhost] ~/w/a/sed$ sed -i "s#test#node#g" 1.txt
[root@localhost] ~/w/a/sed$ cat 1.txt
node
node01
node02
node666

 

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值