我们先编写一个小文档,用于后期举例使用。
[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:直接修改文件的内容,而不是输出到终端