sed的基本用法
认识sed工具的基本选项
sed命令的常用选项如下:
-n(屏蔽默认的输出,默认sed会输出读取文档的全部内容)
-r(让sed支持扩展正则)
-i (sed直接修改源文件,默认sed只是通过内存临时修改文件,源文件无影响)
sed命令的常用指令如下:
sed指令p(显示)、d(删除)、s(替换)、i(在行前写入)、a(在行后追加)、c
(替换行)、r(读)、w(写)等常见的操作
sed用法
用法一、
前置命令 | sed 选项 指令
用法二、
sed 选项 指令 文件
p使用行号做定址符:
[root@server0 ~]#vim text.txt
[root@server0 ~]# sed -n 'p' text.txt //-n是屏蔽默认输出,只显示一次所有行
[root@server0 ~]#sed -n '1p' text.txt //只打印第一行在屏幕上
[root@server0 ~]#sed -n '2,4p' text.txt //打印第二行到第四行在屏幕上
[root@server0 ~]#sed -n '2p;4p' text.txt //打印第二行和第四行在屏幕上
[root@server0 ~]#sed -n '1~2p' text.txt //打印奇数行在屏幕上
[root@server0 ~]#sed -n '1,+2p' text.txt //打印从第一行开始在加两行
p使用正则做定址符:
[root@server0 ~]#sed -n '/root/p' /etc/passwd //搜索包含root的行
[root@server0 ~]#sed -n '/^root/p' /etc/passwd //搜索以root开头的行
[root@server0 ~]#sed -n '/root$/p' /etc/passwd //搜索以root结尾的行
[root@server0 ~]#sed -n '/ro\{1,\}/p' /etc/passwd //搜索以ro开头的字串,并且出现一次以及一次以上的行
-r 支持扩展正则
sed -n -r '/ro{1,}/p' /ect/passwd //使用扩展正则搜索以ro开头的字串,并且出现一次以及一次以上的行
=显示行号
[root@server0 ~]#sed -n '=' text.txt //显示所有行的行号
[root@server0 ~]#sed -n '$=' text.txt //显示最后一行的行号
[root@server0 ~]#sed -n '/root/=' text.txt //显示有root字串的行的行号
d 做定址符 与p用法相似
[root@server0 ~]#sed 'd' text.txt //删除文本中所有行
[root@server0 ~]#sed '1d' text.txt //删除文本中第一行
[root@server0 ~]#sed '1,2d' text.txt //删除文本中第一行到第二行
[root@server0 ~]#sed '1,+2d' text.txt //删除文本中从第一行开始在加两行
[root@server0 ~]#sed '1~2d' text.txt //删除奇数行
[root@server0 ~]#sed '/root/d' text.txt //删除有root的行
-i 对文件进行修改
[root@server0 ~]#sed -i ‘p’ text.txt //将源本显示在屏幕的结果保存到文本中
[root@server0 ~]#sed -i '1d' text.txt //删除第一行后,保存文件
[root@server0 ~]#sed -i '$d' text.txt //删除最后一行,保存文件
s 替换功能
[root@server0 ~]#sed 's/2017/****/' test.txt //使用s替换指令,将文本每行符合要求的第一个2017替换为****
[root@server0 ~]#sed 's/2017/****/g' test.txt //使用s替换指令,将文本中每行符合要求的所有2017替换为****
[root@server0 ~]#sed 's/2017/****/2' test.txt //使用s替换指令,将文本中每行符合要求的第二个2017替换为****
[root@server0 ~]#sed 's/2017//2' test.txt //使用s替换指令,将文本中每行符合要求第二个2017替换为空,相当于删除2017
i指令 在行前输入
[root@server0 ~]#sed 'i 123456' text.txt //在text.txt文件中每行前,追加123456
[root@server0 ~]#sed '2i 123456' text.txt //在text.txt文件中第二行前,追加123456
a指令 在行后输出
[root@server0 ~]# sed 'a123456' text.txt //在text.txt文件中每行后,追加123456
[root@server0 ~]#sed '2a123456' text.txt //在text.txt文件中第二行后,追加123456
c指令 替换行
[root@server0 ~]#sed 'c123456' text.txt //将text.txt文件每行替换为123456
[root@server0 ~]#sed '1c123456' text.txt //将text.txt文件第一行替换为123456
r读某文件的内容到目录文件
[root@server0 ~]#sed 'r a.txt' text.txt //读取a.txt文件并输入到text.txt文件每行的行后
[root@server0 ~]#sed '2r a.txt' text.txt //读取a.txt文件并输入到text.txt文件第二行的行后
w 写入目标文件的内容到其他文档
[root@server0 ~]#sed 'w a.txt' text.txt // 将text.txt文件里的内容覆盖到a.txt文件中,如果目标文件不存在 则自动创建