Sed命令详解+如何替换换行符

基础用法详解

(1)第一行之后添加一行

[root@localhost ~]# nl file.txt | sed "1a add text"
     1  wtmp begins Mon Feb 24 14:26:08 2014
add text
     2  192.168.0.1
     3  162.12.0.123
     4  this is the last line

(2)第一行之前添加一行

[root@localhost ~]# nl file.txt | sed "1i add text"
add text
     1  wtmp begins Mon Feb 24 14:26:08 2014
     2  192.168.0.1
     3  162.12.0.123
     4  this is the last line

(3)删除第2,3行

[root@localhost ~]# nl file.txt | sed "2,3d"
     1  wtmp begins Mon Feb 24 14:26:08 2014
     4  this is the last line

(4)打印第2,3行

[root@localhost ~]# sed -n "2,3p" file.txt 
192.168.0.1
162.12.0.123

这里要提到的是,尽量使用-n,不然会出现这样的结果

[root@localhost ~]# sed "2,3p" file.txt 
wtmp begins Mon Feb 24 14:26:08 2014
192.168.0.1
192.168.0.1
162.12.0.123
162.12.0.123
this is the last line

(5)把168换成169
先看源文件

[root@localhost ~]# cat file.txt 
wtmp begins Mon Feb 24 14:26:08 2014
192.168.0.1
162.12.0.123
this is the last line

处理后

[root@localhost ~]# sed "s/168/169/g" file.txt 
wtmp begins Mon Feb 24 14:26:08 2014
192.169.0.1
162.12.0.123
this is the last line

(6)插入多行

[root@localhost ~]# nl file.txt | sed "2afirst\nsecond" file.txt 
wtmp begins Mon Feb 24 14:26:08 2014
192.168.0.1
first
second
162.12.0.123
this is the last line

(7)匹配数据,然后进行操作
只需要在上述的基础上加上正则匹配

sed "/匹配的模式/处理的方式" file.txt

sed "/^root/d" file.txt 对开始有root的删除
例如
匹配begin,并删除改行

[root@localhost ~]# nl file.txt | sed "/begin/d"
     2  192.168.0.1
     3  162.12.0.123
     4  this is the last line

匹配123,并且把含有123的行162都替换成172

[root@localhost ~]# nl file.txt | sed "/123/{s/162/172/g;q}"
     1  wtmp begins Mon Feb 24 14:26:08 2014
     2  192.168.0.1
     3  172.12.0.123
     4  this is the last line

这里大括号{}里可以执行多个命令,用;隔开即可,q是退出
(8)连续编辑 -e
删除第二行,并且匹配把last替换成new

     1  wtmp begins Mon Feb 24 14:26:08 2014
     3  162.12.0.123
     4  this is the new line

(9)直接修改文件,切记不要修改系统文件

[root@localhost ~]# sed -i "/begin/{s/24/25/g}" file.txt 
[root@localhost ~]# cat file.txt 
wtmp begins Mon Feb 25 14:26:08 2014
192.168.0.1
162.12.0.123
this is the last line

一个比较有趣的例子

如何替换\n也就是把所有的行都归为一行
第一种方式

sed ':a;N;$!ba;s/\n/ /g' file.txt

[root@localhost ~]# sed ':a;N;$!ba;s/\n/ /g' file.txt 
wtmp begins Mon Feb 25 14:26:08 2014 192.168.0.1 162.12.0.123 this is the last line

第二种方式

tr "\n" " " < file.txt

[root@localhost ~]# tr "\n" " " < file.txt 
wtmp begins Mon Feb 25 14:26:08 2014 192.168.0.1 162.12.0.123 this is the last line last linen

你可能感兴趣的:(Sed命令详解+如何替换换行符)