天天看点

sed正则表达式匹配批量替换文件中的内容

**sed命令介绍**

sed是一种流编辑器,它是文本处理中非常有用的工具,能够完美的配合正则表达式使用,功能不同凡响。处理时,把当前处理的行存储在临时缓冲区中,称为『模式空间』(pattern space),接着用sed命令处理缓冲区中的内容,处理完成后,把缓冲区的内容送往屏幕。接着处理下一行,这样不断重复,直到文件末尾。文件内容并没有改变,除非你使用重定向存储输出。sed主要用来自动编辑一个或多个文件,简化对文件的反复操作,编写转换程序等。

**基本语法**

sed的命令格式:sed [options] 'command' file(s)
sed的脚本格式:sed [options] -f scriptfile file(s)
           

**参数**

参数	完整参数	说明
-e script	-expression=script	以选项中的指定的script来处理输入的文本文件
-f script	–files=script	以选项中的指定的script文件来处理输入的文本文件
-h	–help	显示帮助
-n	–quiet --silent	仅显示script处理后的结果
-V	–version	显示版本信息
           

命令

命令	说明
d	删除,删除选择的行
D	删除模板块的第一行
s	替换指定字符
h	拷贝模板块的内容到内存中的缓冲区
H	追加模板块的内容到内存中的缓冲区
g	获得内存缓冲区的内容,并替代当前模板块中文本
G	获得内存缓冲区的内容,并追加到当前模板块文本的后面
l	列表不能打印字符的清单
n	读取下一个输入行,用下一个命令处理新的行而不是第一个命令
N	追加下一个输入行到模板块后面并在二者间嵌入一个新行,改变当前行号码
p	打印模板块的行
P	打印模板块的第一行
q	退出sed
b label	分支到脚本中带有标记的地方,如果分支不存在则分支到脚本的末尾
r file	从file中读行
t label	if分支,从最后一行开始,条件一旦满足或者T,t命令,将导致分支到带有标号的命令处,或者到脚本的末尾
T label	错误分支,从最后一行开始,一旦发生错误或者T,t命令,将导致分支到带有标号的命令处,或者到脚本的末尾
w file	写并追加模板块到file末尾
W file	写并追加模板块的第一行到file末尾
!	表示后面的命令对所有没有被选定的行发生作用
=	打印当前行号
           

接下来主要介绍替换功能

替换的使用
命令	说明
g	表示行内全面替换
p	表示打印行
w	表示把行写入一个文件
x	表示互换模板块中的文本和缓冲区中的文本
y	表示把一个字符翻译为另外的字符(但是不用于正则表达式)
\1	子串匹配标记
&	已匹配字符串标记
           

当然要使用其功能需要对正则表达式有一定了解。这里不在介绍。

使用实例

创建文档

[[email protected] software]# cat test.txt 
you are children
hello boy
this is school
hello teacher
hello,today is sunday
come on
nice to meet you
hello,this talk ga ga ga 
           

开始练习:

替换hello为word,并打印到屏幕

[[email protected] software]# sed 's/hello/word/' test.txt 
you are children
word boy
this is school
word teacher
word,today is sunday
come on
nice to meet you
word,this talk ga ga ga
           

从开始位置替换,并加上回车

[[email protected] software]# sed 's/^hello/word\n/' test.txt 
you are children
word
 boy
this is school
word
 teacher
word
,today is sunday
come on
nice to meet you
word
,this talk ga ga ga 
           

大多数我们并不希望看到没有匹配到的行,那么直输出匹配内容一行更友好

[[email protected] software]# sed -n 's/hello/word/p' test.txt 
word boy
word teacher
word,today is sunday
word,this talk ga ga ga 
           

以后会持续根据实际项目更新

实例一:

新装kvm中centos7网卡更改为开机启动

sed正则表达式匹配批量替换文件中的内容

实例二:

关闭selinux配置文件

[[email protected] ~]# cat /etc/selinux/config 

# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
SELINUX=disable
# SELINUXTYPE= can take one of three values:
#     targeted - Targeted processes are protected,
#     minimum - Modification of targeted policy. Only selected processes are protected. 
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted