sed的用法与实例介绍

我们先编写一个小文档,用于后期举例使用。

[danni@vm-xxx study]$ cat SedDemo.txt 
This is a sed text.
I am beautyful.
You are not beautyful.
He is also not beautiful.
Hei Hei.
Are you laugh?
No, you can not do that.
Are you sad?
Oh, It is very good.

sed 替换
sed 's/beautyful/not beautyful/' SedDemo.txt: 把所有的 beautyful 替换为 not beautyful
格式:sed 's/被替换内容/替换的内容/' 文本文件
这里写图片描述


sed多重指令的实现方式
(1)使用分号相隔: sed 's/not beautyful/beautyful/; s/Hei/yeah/' SedDemo.txt

danni@vm-bestgame-18:xxx $ sed 's/not beautyful/beautyful/;s/Hei/teah/' SedDemo.txt 
This is a sed text.
I am beautyful.
You are beautyful.
He is also not beautiful.
teah Hei.
Are you laugh?
No, you can not do that.
Are you sad?
Oh, It is very good.

(2)在每个指令前放置 -e

danni@vm-bestgame-18:xxx  $ sed -e 's/not beautyful/beautyful/' -e 's/Hei/teah/' SedDemo.txt
This is a sed text.
I am beautyful.
You are beautyful.
He is also not beautiful.
teah Hei.
Are you laugh?
No, you can not do that.
Are you sad?
Oh, It is very good.

(3)使用shell的分行指令功能

[danni@vm-xxx study]$ sed '
> s/not beautyful/beautyful/
> s/Hei/yeah/' SedDemo.txt 

这里写图片描述

sed 实现多个条件
格式:sed '/s/\(A条件\|B条件\)//p
其中:多个条件使用 | 分割,多个条件使用括号 () 括起来,() 和 | 都需要转义
其中:/p 表示打印

danni@vm-bestgame-18:xxx  $ echo -e "/a/b/c/d" | sed -n 's/\(\/$\|$\)//p'
/a/b/c/d
danni@vm-bestgame-18:xxx  $ echo -e "/a/b/c/d/" | sed -n 's/\(\/$\|$\)//p'  
/a/b/c/d

sed 脚本文件
当命令很少的时候,我们采取上述直接在命令行输入是可行的。但是当命令很长的时候,再输入这么长的脚本是不切合实际的。不过,我们可以通过创建脚本文件,吧要执行的命令书写在脚本文件中即可。
通过 -f 选项来指定命令行上的脚本文件的名字:sed -f scriptfile file ,scriptfile 即编写的脚本文件,file 即要操作的文本文件
编写脚本文件:vim SedScript

[danni@vm-xxx study]$ cat SedScript 
s/not beautyful/beautyful/
s/Hei/yeah/

执行脚本文件: sed -f SedScript SedDemo.txt

[danni@vm-xxx study]$ sed -f SedScript SedDemo.txt 
This is a sed text.
I am beautyful.
You are beautyful.
He is also beautyful.
yeah Hei.
Are you laugh?
No, you can not do that.
Are you sad?
Oh, It is very good.

sed默认输出是输出到终端,如果想把sed的输出重定向到另一个程序中,需要在后面指定一个I/O重定向符号。
sed -f scriptfile file > newfile



sed -n 命令:
-n:只打印匹配的模式行的内容,不会打印文档中全部内容



sed -e 命令:
-e:用来传递多个编辑命令式



sed -i 命令:
-i:直接修改文件的内容,而不是输出到终端

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值