linux -- sed命令

发布时间 2023-07-20 16:33:47作者: 周杰森

作用

sed命令可以根据一套规则编辑数据!

#test.txt原本内容
[dmadmin@DEMPSRV2 test]$ cat test.txt
jason ia handsome!
kevin is handsome too!
other are not!

 

替换命令:s

# handsome:需要被替换的文本; cool:替换后的文本   g:全部替换
[dmadmin@DEMPSRV2 test]$ sed 's/handsome/cool/g' test.txt
jason ia cool!
kevin is cool too!
other are not!

 

删除命令:d

# 删除第二行数据
[dmadmin@DEMPSRV2 test]$ sed '2d' test.txt
jason ia handsome!
other are not!

 

在指定行后面加一行a, 在指定行前面加一行i

# 在第二行后面加一行new line      如果你想将一个多行数据添加到数据流中,只需对要插入或附加的文本中的每一行末尾(除最后一行)添加反斜线即可
[dmadmin@DEMPSRV2 test]$ sed '2a\
> new line' test.txt
jason ia handsome!
kevin is handsome too!
new line
other are not!


# 在第二行前面加一行“new line before 2.”     
[dmadmin@DEMPSRV2 test]$ sed '2i\
> new line before 2.' test.txt
jason ia handsome!
new line before 2.
kevin is handsome too!
other are not!

 

指定行内容替换成写入的信息:c

# 第2行替换成change to life
[dmadmin@DEMPSRV2 test]$ sed '2c\
> change to life
> ' test.txt
jason ia handsome!
change to life
other are not!