三劍客之sed常用操作
Sed是一個強大的文本處理工具
可以采用正則匹配,對文本進行插入刪除修改等操作
Sed處理的時候,一次處理一行,每一次把當前處理的存放在臨時緩沖區,處理完後輸出緩沖區內容到屏幕,然後把下一行讀入緩沖區,如此重復,直到結尾。
1、命令格式和參數
sed [-nefr] [動作] 文件
參數:
-n 安靜模式,在sed處理的時候,所有來自STDIN的數據都會被輸出到終端,加上-n會只輸出處理的哪行
-e 直接在命令列上進行sed動作編輯
-f 直接將sed的動作寫在文件內
-r sed動作支持延伸的正則表達(默認只是基礎正則)
-i 直接修改文件內容(慎用,尤其是用系統文件做練習的時候)
動作:
a append:增加,在當前行的下一行增加
c :取代,取代n1到n2之間的行
d delete:刪除
i 插入,目前行的上一行插入
p 打印,常常與-n使用
s 取代,s/old/new/g
2、基礎用法詳解
(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)第一行之前添加一行 copy
[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行 copy
[root@localhost ~]# sed -n "2,3p" file.txt
192.168.0.1
162.12.0.123
這裏要提到的是,盡量使用-n,不然會出現這樣的結果 copy
[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
先看源文件 copy
[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
處理後 copy
[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,並刪除改行 copy
[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 copy
[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
<pre name="code" class="plain">[root@localhost ~]# nl file.txt | sed -e "2d" -e "s/last/new/"
1 wtmp begins Mon Feb 24 14:26:08 2014
3 162.12.0.123
4 this is the new line
(9)直接修改文件,切記不要修改系統文件 copy
[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也就是把所有的行都歸為一行
第一種方式 copy
[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
第二種方式opy
[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常用操作