sed 追加文本类容_干货-Shell编程文本处理三剑客之-sed

sed 工具

sed(Stream EDitor)是一个强大而简单的文本解析转换工具,可以读取文本,并根据指定的条件对文本内容进行编辑(删除、替换、添加、移动等),最后输出所有行或者仅输出处理的某些行。sed 也可以在无交互的情况下实现相当复杂的文本处理操作,被广泛应用于 Shell 脚本中,用以完成各种自动化处理任务。

二、sed 的工作流程主要包括读取、执行和显示三个过程

1.读取:sed 从输入流(文件、管道、标准输入)中读取一行内容并存储到临时的缓冲区中(又称模式空间,pattern space)。 2.执行:默认情况下,所有的 sed 命令都在模式空间中顺序地执行,除非指定了行的地址,否则 sed 命令将会在所有的行上依次执行。 3.显示:发送修改后的内容到输出流。再发送数据后,模式空间将会被清空。在所有的文件内容都被处理完成之前,上述过程将重复执行,直至所有内容被处理完。

注意:默认情况下,所有的 sed 命令都是在模式空间内执行的,因此输入的文件并不会发生任何变化,除非是用重定向存储输出。

三、语法格式:

06969b2a787a72bbe1fbc7cfa9213d67.png

a89aee4edc35577341dca1df025f00a0.png

sed选项

784cb21e9547037570f0bbc806d9203f.png

示例

# 匹配Python
# 会发现没匹配的行也被打印了,而匹配的行打印了两遍
# 因为sed默认就会把原行进行打印(p是打印command)
sed '/Python/p' file
->Python
->Python
->Java
->Python is good
->Python is good
->Java is perfect
->Php is the best lanuage

# 只打印匹配行,不打印原行
sed -n '/Python/p' file
->Python
->Python is good

# 多个pattern
sed -n -e '/Python/p' -e '/Java/p' file
->Python
->Java
->Python is good
->Java is perfect

# 扩展正则表达式
# 也许你会将上面两个pattern合并在一起:/Python|Java/p.十分可惜,默认sed不支持扩展正则表达式,需要加上-r
sed -n -r '/Python|Java/p' file
->Python
->Java
->Python is good
->Java is perfect

# '批'处理
# 如果我们有很多动作需要操作,可以直接写在文件里,使用-f选项引入动作文件即可,新建multsed.sed(不一定要.sed),内容为:
/Python/p
/Java/p

sed -n -f 'multsed.sed' file
->Python
->Java
->Python is good
->Java is perfect

sed的pattern

匹配模式含义
10command匹配到第10行
10,20command匹配从第10行开始,到第20行结束
10,+5command匹配从第10行开始,到第16行结束
/pattern1/command匹配到pattern1行
/pattern1/,/pattern2/command匹配到pattern1的行开始,到匹配到pattern2的行结束
10,/pattern1/command匹配从第10行开始,到匹配到pattern1的行结束
/pattern1/,10command匹配从匹配到pattern1的行开始,到第10行结束

示例

# 打印指定行号内容
sed -n '2p' file
->Java

# 打印起始行号到终止行号之间的信息(start不能小于1哦)
sed -n '1,3p' file
->Python
->Java
->Python is good

# 指定起始行号,打印后面n行
sed -n '1,+2p' file
->Python
->Java
->Python is good

# 打印匹配行
sed -n '/Python/p' file
->Python
->Python is good

# 打印两个匹配之间的行
sed -n '/Python/,/good/p' file
->Python
->Java
->Python is good

# 从指定起始行开始到匹配行结束
sed -n '2,/good/p' file
->Java
->Python is good

# 从匹配行开始到指定的行结束(如果匹配到的行号小于指定的结束行那就只会显示匹配行信息)
sed -n '/good/,4p' file
->Python is good
->Java is perfect

sed -n '/good/,2p' file
->Python is good

sed的命令

类别命令含义
增加a行后追加,在当前行下面增加一行指定内容。
行前追加i
外部文件读入,行后追加r
匹配行写入外部文件w
修改s/old/new将行内第一个old替换为new
全局替换s/old/new/g将行内全部old替换为new
不区别大小写全局替换s/old/new/ig将行内old全部替换为new,忽略大小写

示例

# 在第1行后追加内容(如果需要修改文件则需要加上-i选项)
sed '1aScala' file
->Python
->Scala
->Java
->Python is good
->Java is perfect
->Php is the best lanuage

# 在匹配到的行前加上内容
sed '/Python/iHello Python' file
->Hello Python
->Python
->Java
->Hello Python
->Python is good
->Java is perfect
->Php is the best lanuage

# 读入外部文件读入(不写匹配模式则在每一行后面都追加数据)
sed 'rmultsed.sed' file
->Python
->/Python/p
->/Java/p
->Java
->/Python/p
->/Java/p
->Python is good
->/Python/p
->/Java/p
->Java is perfect
->/Python/p
->/Java/p
->Php is the best lanuage
->/Python/p
->/Java/p

# 将匹配到的行信息写入外部文件
sed '/Python/wpython.txt' file

# 将行内第一个匹配替换
sed -n 's/Python/Java/p' file
->Java Python python
->Java is good Python is good

# 将行内所有匹配替换
sed -n 's/Python/Java/gp' file
->Java Java python
->Java is good Java is good

# 将行内所有匹配替换(忽略大小写)
sed -n 's/Python/Java/igp' file
->Java Java Java
->Java is good Java is good

# 替换第3个匹配后的所有old(忽略大小写)
sed -n 's/Python/Java/3igp' file
->Python Python Java

# 显示匹配行行号
sed -n '/Python/=' file
->1
->3

# 如果pattern使用的是变量的值那么必须使用双引号,除非你也给变量标上单引号
var1=Python
sed -n '/$var1/=' file
->
sed -n "/$var1/=" file
->1
->3

sed -n '/'$var1'/=' file
->1
->3

sed 命令的基本用法

(1)输出所有内容,等同于 cat test.txt

[root@localhost opt]# sed -n 'p' test.txt 
# This is the main Apache HTTP server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# In particular, see 
# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do.  They're here only as hints or reminders.  If you are unsure
# consult the online docs. You have been warned.  
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path.  If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so 'log/access_log'
# with ServerRoot set to '/www' will be interpreted by the
# server as '/www/log/access_log', where as '/log/access_log' will be
# interpreted as '/log/access_log'.
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path.  If you point
# ServerRoot at a non-local disk, be sure to specify a local disk on the

(2)输出第 3 行

[root@localhost opt]# sed -n '3p' test.txt 
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.

(3)输出 3~5 行

[root@localhost opt]# sed -n '3,5p' test.txt 
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# In particular, see 
# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>

(4)输出所有奇数行,n 表示读入下一行资料

[root@localhost opt]# sed -n 'p;n' test.txt 
# This is the main Apache HTTP server configuration file.  It contains the
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
#
# what they do.  They're here only as hints or reminders.  If you are unsure
#
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# with "/", the value of ServerRoot is prepended -- so 'log/access_log'
# server as '/www/log/access_log', where as '/log/access_log' will be
# ServerRoot: The top of the directory tree under which the server's
#
# ServerRoot at a non-local disk, be sure to specify a local disk on the

(5)输出所有偶数行,n 表示读入下一行资料

[root@localhost opt]# sed -n 'n;p' test.txt 
# configuration directives that give the server its instructions.
# In particular, see 
# for a discussion of each configuration directive.
# Do NOT simply read the instructions in here without understanding
# consult the online docs. You have been warned.  
# Configuration and logfile names: If the filenames you specify for many
# server will use that explicit path.  If the filenames do *not* begin
# with ServerRoot set to '/www' will be interpreted by the
# interpreted as '/log/access_log'.
#
# configuration, error, and log files are kept.
# Do not add a slash at the end of the directory path.  If you point

(6)输出第 1~5 行之间的奇数行(第 1、3、5 行)

[root@localhost opt]# sed -n '1,5{p;n}' test.txt 
# This is the main Apache HTTP server configuration file.  It contains the
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>

(7)输出第 10 行至文件尾之间的偶数行

[root@localhost opt]# sed -n '10,${n;p}' test.txt 
#
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# with "/", the value of ServerRoot is prepended -- so 'log/access_log'
# server as '/www/log/access_log', where as '/log/access_log' will be
# ServerRoot: The top of the directory tree under which the server's
#
# ServerRoot at a non-local disk, be sure to specify a local disk on the

在执行“sed –n‘10,${n;p}’test.txt”命令时,读取的第 1 行是文件的第 10 行,读取的第 2 行是文件的第 11 行,依此类推,所以输出的偶数行是文件的第 11 行、13 行直至文件结尾,其中包括空行。

5.sed 命令结合正则表达式

(1)输出包含the的行

[root@localhost opt]# sed -n '/the/p' test.txt 
# This is the main Apache HTTP server configuration file.  It contains the
# configuration directives that give the server its instructions.
# Do NOT simply read the instructions in here without understanding
# what they do.  They're here only as hints or reminders.  If you are unsure
# consult the online docs. You have been warned.  
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path.  If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so 'log/access_log'
# with ServerRoot set to '/www' will be interpreted by the
# ServerRoot: The top of the directory tree under which the server's
# Do not add a slash at the end of the directory path.  If you point
# ServerRoot at a non-local disk, be sure to specify a local disk on the

(2)输出从第 4 行至第一个包含 the的行

[root@localhost opt]# sed -n '4,/the/p' test.txt 
# In particular, see 
# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding

(3)输出包含the 的行所在的行号,等号(=)用来输出行号

[root@localhost opt]# sed -n '/the/=' test.txt 
1
2
8
9
10
12
13
14
15
16
21
24
25

(4)输出以PI 开头的行

[root@localhost opt]# sed -n '/^PI/P' test.txt 
PI=3.14159265358979323846264338324990142

(5)输出以数字结尾的行

[root@localhost opt]# sed -n '/[0-9]$/p' test.txt 
PI=3.14159265358979323846264338324990142

(6)输出包含单词wood 的行,<、>代表单词边界

[root@localhost opt]# sed -n '/<wood>/p' test.txt 
a wood cross!

6.删*除符合条件的文本***(d)**

以下示例分别演示了 sed 命令的几种常用删除用法。

下面命令中 nl 命令用于计算文件的行数,结合该命令可以更加直观地查看到命令执行的结果。

(1)删除第 3 行

[root@localhost opt]# nl test.txt | sed '3d'
     1  # This is the main Apache HTTP server configuration file.  It contains the
     2  # configuration directives that give the server its instructions.
     4  # In particular, see 
     5  # <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
     6  # for a discussion of each configuration directive.
     7  #
     8  # Do NOT simply read the instructions in here without understanding

(2)删除第 3~5 行

[root@localhost opt]# nl test.txt | sed '3,5d'
     1  # This is the main Apache HTTP server configuration file.  It contains the
     2  # configuration directives that give the server its instructions.
     6  # for a discussion of each configuration directive.
     7  #
     8  # Do NOT simply read the instructions in here without understanding
     9  # what they do.  They're here only as hints or reminders.  If you are u

(3)删除包含cross 的行,原本的第 8 行被删除

[root@localhost opt]# nl test.txt | sed '/cross/d'
     1  # This is the main Apache HTTP server configuration file.  It contains the
     2  # configuration directives that give the server its instructions.
     3  # See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
     4  # In particular, see 
     5  # <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
     6  # for a discussion of each configuration directive.
     7  # shan skmks flmdlsks lsmls
     9  # shan yebd osjs ojsd ocok 
    10  # what they do.  They're here only as hints or reminders.  If you are unsure
    11  # consult the online docs. You have been warned.

(4)删除不包含cross 的行,用!符号表示取反操作,如*'/cross/!d'*

[root@localhost opt]# nl test.txt | sed '/cross/ ! d'
     8  # Do NOT simply read the instructions cross in here without understanding
    27  a wood cross!

(5)删除以小写字母开头的行

[root@localhost opt]# sed '/^[a-z]/d' test.txt 
This is the main Apache HTTP server configuration file.  It contains the
See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
In particular, see 
URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
Do NOT simply read the instructions cross in here without understanding
Configuration and logfile names: If the filenames you specify for many
ServerRoot: The top of the directory tree under which the server's
Do not add a slash at the end of the directory path.  If you point
ServerRoot at a non-local disk, be sure to specify a local disk on the
PI=3.14159265358979323846264338324990142

(6)删除以"."结尾的行

[root@localhost opt]# sed '/.$/d' test.txt 
This is the main Apache HTTP server configuration file.  It contains the
In particular, see 
URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
shan skmks flmdlsks lsmls
Do NOT simply read the instructions cross in here without understanding
shan yebd osjs ojsd ocok 
what they do.  They're here only as hints or reminders.  If you are unsure
consult the online docs. You have been warned  
Configuration and logfile names: If the filenames you specify for many
of the server's control files begin with "/" (or "drive:/" for Win32), the
server will use that explicit path.  If the filenames do *not* begin
with "/", the value of ServerRoot is prepended -- so 'log/access_log'
with ServerRoot set to '/www' will be interpreted by the
server as '/www/log/access_log', where as '/log/access_log' will be
ServerRoot: The top of the directory tree under which the server's
Do not add a slash at the end of the directory path.  If you point
ServerRoot at a non-local disk, be sure to specify a local disk on the
PI=3.14159265358979323846264338324990142
a wood cross!

(7)删除所有空行

[root@localhost opt]# sed '/^$/d' test.txt 
This is the main Apache HTTP server configuration file.  It contains the
configuration directives that give the server its instructions.
See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
In particular, see 
URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
for a discussion of each configuration directive.
shan skmks flmdlsks lsmls
Do NOT simply read the instructions cross in here without understanding
shan yebd osjs ojsd ocok 
what they do.  They're here only as hints or reminders.  If you are unsure
consult the online docs. You have been warned  
Configuration and logfile names: If the filenames you specify for many
of the server's control files begin with "/" (or "drive:/" for Win32), the
server will use that explicit path.  If the filenames do *not* begin
with "/", the value of ServerRoot is prepended -- so 'log/access_log'
with ServerRoot set to '/www' will be interpreted by the
server as '/www/log/access_log', where as '/log/access_log' will be
interpreted as '/log/access_log'.
ServerRoot: The top of the directory tree under which the server's
configuration, error, and log files are kept.
Do not add a slash at the end of the directory path.  If you point
ServerRoot at a non-local disk, be sure to specify a local disk on the
PI=3.14159265358979323846264338324990142
a wood cross!

(8)若是删除重复的空行,即连续的空行只保留一个, 执行“ sed –e ‘/^$/{n;/^$/d}’test.txt”命令即可实现。其效果与“cat -s test.txt”相同,n 表示读下一行数据。

[root@localhost opt]# sed -e '/^$/{n;/^$/d}' test.txt 
This is the main Apache HTTP server configuration file.  It contains the
configuration directives that give the server its instructions.
See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
In particular, see 
URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
for a discussion of each configuration directive.
shan skmks flmdlsks lsmls
Do NOT simply read the instructions cross in here without understanding

shan yebd osjs ojsd ocok 

what they do.  They're here only as hints or reminders.  If you are unsure

consult the online docs. You have been warned  

Configuration and logfile names: If the filenames you specify for many

of the server's control files begin with "/" (or "drive:/" for Win32), the

server will use that explicit path.  If the filenames do *not* begin

with "/", the value of ServerRoot is prepended -- so 'log/access_log'

with ServerRoot set to '/www' will be interpreted by the

server as '/www/log/access_log', where as '/log/access_log' will be

interpreted as '/log/access_log'.

ServerRoot: The top of the directory tree under which the server's

configuration, error, and log files are kept.

Do not add a slash at the end of the directory path.  If you point

ServerRoot at a non-local disk, be sure to specify a local disk on the

PI=3.14159265358979323846264338324990142

a wood cross!

*7.替换符合条件的文本*

在使用 sed 命令进行替换操作时需要用到 s(字符串替换)、c(整行/整块替换)、y(字符转换)命令选项,常见的用法如下:

(1)将每行中的第一个the 替换为 THE

[root@localhost opt]# sed 's/the/THE/' test.txt 
THE this bad
ServerRoot: The top of THE directory tree under which the server's
configuration, error, and log files are kept.
Do not add a slash at THE end of the directory path.  If you point
ServerRoot at a non-local disk, be sure to specify a local disk on THE
PI=3.14159265358979323846264338324990142
a wood cross!

(2)将每行中的第 3 个l 替换为L

[root@localhost opt]# sed 's/l/L/3' test.txt 
the this bad
ServerRoot: The top of the directory tree under which the server's
configuration, error, and log files are kept.
Do not add a slash at the end of the directory path.  If you point
ServerRoot at a non-local disk, be sure to specify a Local disk on the
PI=3.14159265358979323846264338324990142
a wood cross!

(3)将文件中的所有the 替换为THE

[root@localhost opt]# sed 's/the/THE/g' test.txt 
THE this bad
ServerRoot: The top of THE directory tree under which THE server's
configuration, error, and log files are kept.
Do not add a slash at THE end of THE directory path.  If you point
ServerRoot at a non-local disk, be sure to specify a local disk on THE
PI=3.14159265358979323846264338324990142
a wood cross!

(4)将文件中的所有o 删除(替换为空串)

[root@localhost opt]# sed 's/o//g' test.txt 
the this bad
ServerRt: The tp f the directry tree under which the server's
cnfiguratin, errr, and lg files are kept.
D nt add a slash at the end f the directry path.  If yu pint
ServerRt at a nn-lcal disk, be sure t specify a lcal disk n the
PI=3.14159265358979323846264338324990142
a wd crss!

(5)在每行行首插入#号

[root@localhost opt]# sed 's/^/#/g' test.txt 
#the this bad
#ServerRoot: The top of the directory tree under which the server's
#configuration, error, and log files are kept.
#Do not add a slash at the end of the directory path.  If you point
#ServerRoot at a non-local disk, be sure to specify a local disk on the
#PI=3.14159265358979323846264338324990142
#a wood cross!

(6)在包含the 的每行行首插入#号

[root@localhost opt]# sed '/the/s/^/#/' test.txt 
#the this bad
#ServerRoot: The top of the directory tree under which the server's
configuration, error, and log files are kept.
#Do not add a slash at the end of the directory path.  If you point
#ServerRoot at a non-local disk, be sure to specify a local disk on the
PI=3.14159265358979323846264338324990142
a wood cross!

(7)在每行行尾插入字符串EOF

[root@localhost opt]# sed 's/$/EOF/' test.txt 
the this badEOF
ServerRoot: The top of the directory tree under which the server'sEOF
configuration, error, and log files are kept.EOF
Do not add a slash at the end of the directory path.  If you pointEOF
ServerRoot at a non-local disk, be sure to specify a local disk on theEOF
PI=3.14159265358979323846264338324990142EOF
a wood cross!EOF

(8)将第 3~5 行中的所有the 替换为 THE

root@localhost opt]# sed '3,5s/the/THE/' test.txt 
the this bad
ServerRoot: The top of the directory tree under which the server's
configuration, error, and log files are kept.
Do not add a slash at THE end of the directory path.  If you point
ServerRoot at a non-local disk, be sure to specify a local disk on THE
PI=3.14159265358979323846264338324990142
a wood cross!

(9)将包含the 的所有行中的o 都替换为 O

[root@localhost opt]# sed '/the/s/o/O/g' test.txt 
the this bad
ServerROOt: The tOp Of the directOry tree under which the server's
configuration, error, and log files are kept.
DO nOt add a slash at the end Of the directOry path.  If yOu pOint
ServerROOt at a nOn-lOcal disk, be sure tO specify a lOcal disk On the
PI=3.14159265358979323846264338324990142
a wood cross!

9.迁移符合条件的文本

H,复制到剪贴板; g、G,将剪贴板中的数据覆盖/追加至指定行; w,保存为文件; r,读取指定文件; a,追加指定内容

(1)将包含the 的行迁移至文件末尾,{;}用于多个操作

[root@localhost opt]# sed '/the/{H;d};$G' test.txt 
configuration, error, and log files are kept.
PI=3.14159265358979323846264338324990142
a wood cross!
the this bad
ServerRoot: The top of the directory tree under which the server's
Do not add a slash at the end of the directory path.  If you point
ServerRoot at a non-local disk, be sure to specify a local disk on the

(2)将第 1~5 行内容转移至第 17 行后

[root@localhost opt]# sed '1,5{H;d};17G' test.txt 
PI=3.14159265358979323846264338324990142
a wood cross!
1
2
3
4
5
6
7
8
9
2
the this bad
ServerRoot: The top of the directory tree under which the server's
configuration, error, and log files are kept.
Do not add a slash at the end of the directory path.  If you point
ServerRoot at a non-local disk, be sure to specify a local disk on the
32
43
224
43
142
11
ew
23

(3)将包含the 的行另存为文件out.file

[root@localhost opt]# sed '/the/w out.file' test.txt 
the this bad
ServerRoot: The top of the directory tree under which the server's
configuration, error, and log files are kept.
Do not add a slash at the end of the directory path.  If you point
ServerRoot at a non-local disk, be sure to specify a local disk on the
PI=3.14159265358979323846264338324990142
a wood cross!
1
2
3
[root@localhost opt]# cat out.file 
the this bad
ServerRoot: The top of the directory tree under which the server's
Do not add a slash at the end of the directory path.  If you point
ServerRoot at a non-local disk, be sure to specify a local disk on the

(4)将文件/etc/hostname 的内容添加到包含the 的每行以后

[root@localhost opt]# sed '/the/r/etc/hostname' test.txt 
the this bad
localhost.localdomain
ServerRoot: The top of the directory tree under which the server's
localhost.localdomain
configuration, error, and log files are kept.
Do not add a slash at the end of the directory path.  If you point
localhost.localdomain
ServerRoot at a non-local disk, be sure to specify a local disk on the
localhost.localdomain
PI=3.14159265358979323846264338324990142
a wood cross!
1
2
3

(5)在第 3 行后插入一个新行,内容为 New

[root@localhost opt]# sed '3aNEW' test.txt 
the this bad
ServerRoot: The top of the directory tree under which the server's
configuration, error, and log files are kept.
NEW
Do not add a slash at the end of the directory path.  If you point
ServerRoot at a non-local disk, be sure to specify a local disk on the
PI=3.14159265358979323846264338324990142
a wood cross!
1
2

(6)在包含the 的每行后插入一个新行,内容为 New

[root@localhost opt]# sed '/the/aNEW' test.txt 
the this bad
NEW
ServerRoot: The top of the directory tree under which the server's
NEW
configuration, error, and log files are kept.
Do not add a slash at the end of the directory path.  If you point
NEW
ServerRoot at a non-local disk, be sure to specify a local disk on the
NEW
PI=3.14159265358979323846264338324990142
a wood cross!
1
2

(7)在第 3 行后插入多行内容,中间的n 表示换行

[root@localhost opt]# sed '3aNew1nNew2' test.txt 
the this bad
ServerRoot: The top of the directory tree under which the server's
configuration, error, and log files are kept.
New1
New2
Do not add a slash at the end of the directory path.  If you point
ServerRoot at a non-local disk, be sure to specify a local disk on the
PI=3.14159265358979323846264338324990142
a wood cross!
1
2
3

10.使用脚本编辑文件

使用 sed 脚本,将多个编辑指令存放到文件中(每行一条编辑指令),通过“-f”选项来调用。

(1)将第 1~5 行内容转移至第 17 行后

sed '1,5{H;d};17G' test.txt

以上操作可以改用脚本文件方式:

[root@localhost opt]# vim opt.list
1,5H
1,5d
17G

[root@localhost opt]# sed -f opt.list test.txt 
PI=3.14159265358979323846264338324990142
a wood cross!
1
2
3
4
5
6
7
8
9
2
the this bad
ServerRoot: The top of the directory tree under which the server's
configuration, error, and log files are kept.
Do not add a slash at the end of the directory path.  If you point
ServerRoot at a non-local disk, be sure to specify a local disk on the
32
43
224
43
142
11
ew
23

如果pattern使用的是变量的值那么必须使用双引号,除非你也给变量标上单引号。

反向引用

在sed中引用pattern匹配到的整个串这一行为我们称作反向引用,从下面这一例子来说明。

# 需求:将file按如下方式进行修改Python->Pythoner,Java->Javaer,Php->Phper
# 如果不知道反向引用我们就会多次使用修改命令进行修改
# 如果只是查找这几个单词倒十分简单
sed -n -r '/Python|Java|Php/p' file
# 如果需要替换则有一个难点:下面的这个新字符我们是无法给一个统一的
sed -n -r 's/Python|Java|Php/新字符er/p' file

# 借助反向引用
sed -n -r 's/Python|Java|Php/&er/p' file
->Pythoner Python python
->Javaer java
->Pythoner is good Python is good
->Javaer is perfect
->Phper is the best lanuage

# 除了使用&还可以使用1,2,3等(记住括号),后者可以提取单独的某一个group
sed -n -r 's/(Python|Java|Php)/1er/p' file
->Pythoner Python python
->Javaer java
->Pythoner is good Python is good
->Javaer is perfect
->Phper is the best lanuage

echo -e "Python Java Php" | sed -e "s/(Python) (Java) (Php)/1er 2s 3best/g"
->Pythoner Javas Phpbest

小试牛刀

需求描述:处理一个类似MySQL配置文件my.cnf的文本,示例如下,编写脚本实现以下功能:输出文件有几个段,并且针对每个段可以统计参数总个数。

my.cnf文件内容如下:

# this is read by the standalone daemon and embedded servers
[client]
port=3306
socket=/tmp/mysql.socket

#ThisSegmentForserver
[server]
innodb_buffer_pool_size=91750M
innodb_buffer_pool_instances=8
innodb_buffer_pool_load_at_startup=1
innodb_buffer_pool_dump_at_shutdown=1
innodb_data_file_path=ibdata1:1G:autoextend
innodb_flush_log_at_trx_commit=1
innodb_log_buffer_size=32M
innodb_log_file_size=2G
innodb_log_files_in_group=2
innodb_max_undo_log_size=4G
innodb_undo_directory=undolog
innodb_undo_tablespaces=95

#thisisonlyforthemysqldstandalonedaemon
[mysqld]
port=3306
socket=/tmp/mysql.sock
basedir=/usr/local/mysql
datadir=/data/mysql
pid-file=/data/mysql/mysql.pid
user=mysql
bind-address=0.0.0.0
sort_buffer_size=16M
join_buffer_size=16M
thread_cache_size=3000
interactive_timeout=600
wait_timeout=600

#ThisSegmentFormysqld_safe
[mysqld_safe]
log-error=/var/log/mariadb/mariadb.log
pid-file=/var/run/mariadb/mariadb.pid
max_connections=1000
open_files_limit=65535
thread_stack=512K
external-locking=FALSE
max_allowed_packet=32M

#thisisonlyforembeddedserver
[embedded]
gtid_mode=on
enforce_gtid_consistency=1
log_slave_updates
slave-rows-search-algorithms='INDEX_SCAN,HASH_SCAN'
binlog_format=row
binlog_checksum=1
relay_log_recovery=1
relay-log-purge=1


#usethisgroupforoptionsthatolderserversdon'tunderstand
[mysqld-5.5]
key_buffer_size=32M
read_buffer_size=8M
read_rnd_buffer_size=16M
bulk_insert_buffer_size=64M
myisam_sort_buffer_size=128M
myisam_max_sort_file_size=10G
myisam_repair_threads=1
lock_wait_timeout=3600
explicit_defaults_for_timestamp=1
innodb_file_per_table=1

脚本如下:

#!/bin/bash
# 这里是shell脚本

FILE_NAME="my.cnf"


function get_all_segment
{
    echo "`sed -n '/[.*]/p' $FILE_NAME | sed -r 's/([|])//g'`"
}

# 统计每个段中配置项个数
function count_items_in_segment
{
    #段名
    segname=$1
    itemcount=`sed -n "/[$segname]/,/[.*]/p" $FILE_NAME | grep -v ^# | grep -v ^$ | grep -v "[.*]" | grep -c ""`
    echo $itemcount
}

sum=1
for segname in `get_all_segment`
do
    echo "配置项$sum:$segname `count_items_in_segment $segname`"
    sum=`expr $sum + 1`
done
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值