shell系列8-sed

一. sed概述

sed(stream editor)是流编辑器,可对文本文件和标准输入进行编辑。
sed只是对缓冲区中原始文件的副本进行编辑,并不编辑原始的文件,如果需要保存改动内容,可以选择使用下面两种方法:
重定向
w编辑命令

调用sed有三种方法:

  1. 在Shell命令行输入命令调用sed,格式为:
    sed [选项] ‘sed命令’ 输入文件

  2. 将sed命令插入脚本文件后,然后通过sed命令调用它,格式为:
    sed [选项] -f sed脚本文件 输入文件

  3. 将sed命令插入脚本文件后,最常用的方法是设置该脚本文件为可执行,然后直接执行该脚本文件,格式为:
    ./sed脚本文件 输入文件

第二种方法脚本文件的首行不以#!/bin/sed –f开头;第三种方法脚本文件的首行是#!/bin/sed –f,推荐使用第一种方法和第三种方法

image.png

二. sed实例

sed -n 1p a.txt
打印第一行

sed -n -e ‘/abc/p’ -e ‘/abc/=’ a.txt
‘/abc/p’ 打印含有abc的行
‘/abc/=’ 打印含有abc的行的行号

扫描二维码关注公众号,回复: 13983164 查看本文章

sed -n ‘2,10!p’ a.txt
打印除了第二行到第十行所有的行

sed -n ‘3,/abc/p’ abc.txt
打印从第三行到匹配abc所在的行

sed ‘1,10d’ abc.txt
删除abc.txt的第一到第十行

sed ‘s/abc/ABC/’ abc.txt
将abc.txt中所有的小写abc都替换成大写的ABC,并打印所有行

sed -n ‘s/abc/ABC/p’ abc.txt
将abc.txt中所有的小写abc都替换成大写的ABC,只打印替换的行

sed -n ‘s/abc/ABC/w newabc.txt’ abc.txt
将abc.txt中所有的小写abc都替换成大写的ABC,并将结果保存到newabc.txt文件中,只将修改的行写入到新文件中

追加文本:匹配行后面插入
插入文本:匹配行前面插入
修改文本:将所匹配的文本行利用新文本替代
删除文本:将指定行或指定行范围进行删除

a.txt文件

abc
def
ddfe
fefefefef  adfefef
fefefefef

测试记录:

[root@hp8 tmp]# sed -n 1p a.txt
abc
[root@hp8 tmp]# more a.txt
abc
def
ddfe
fefefefef  adfefef
fefefefef
[root@hp8 tmp]# sed -n -e '/abc/p' -e '/abc/=' a.txt
abc
1
[root@hp8 tmp]# more a.txt
abc
def
ddfe
fefefefef  adfefef
fefefefef
[root@hp8 tmp]# 
[root@hp8 tmp]# sed -n '2,10!p' a.txt
abc
[root@hp8 tmp]# more a.txt
abc
def
ddfe
fefefefef  adfefef
fefefefef
[root@hp8 tmp]# sed -n '3,/abc/p' abc.txt
sed:无法读取 abc.txt:没有那个文件或目录
[root@hp8 tmp]# 
[root@hp8 tmp]# 
[root@hp8 tmp]# sed -n '3,/abc/p' a.txt
ddfe
fefefefef  adfefef
fefefefef
[root@hp8 tmp]# more a.txt
abc
def
ddfe
fefefefef  adfefef
fefefefef
[root@hp8 tmp]# 
[root@hp8 tmp]# sed '1,10d' abc.txt
sed:无法读取 abc.txt:没有那个文件或目录
[root@hp8 tmp]# 
[root@hp8 tmp]# sed '1,10d' a.txt
[root@hp8 tmp]# more a.txt
abc
def
ddfe
fefefefef  adfefef
fefefefef
[root@hp8 tmp]# sed 's/abc/ABC/' a.txt  
ABC
def
ddfe
fefefefef  adfefef
fefefefef
[root@hp8 tmp]# more a.txt
abc
def
ddfe
fefefefef  adfefef
fefefefef
[root@hp8 tmp]# 
[root@hp8 tmp]# sed -n 's/abc/ABC/p' a.txt  
ABC
[root@hp8 tmp]# more a.txt
abc
def
ddfe
fefefefef  adfefef
fefefefef
[root@hp8 tmp]# sed -n 's/abc/ABC/w newabc.txt' a.txt  
[root@hp8 tmp]# more a.txt
abc
def
ddfe
fefefefef  adfefef
fefefefef
[root@hp8 tmp]# more newabc.txt
ABC
[root@hp8 tmp]# 

如果要直接修改文本文件内容,需要使用sed -i

[root@hp8 tmp]# sed  -i 's/abc/ABC/g' a.txt 
[root@hp8 tmp]# more a.txt
ABC
def
ddfe
fefefefef  adfefef
fefefefef

猜你喜欢

转载自blog.csdn.net/u010520724/article/details/124200558