標籤:linux 正則 sed 換行
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)第一行之後添加一行
[[email protected] ~]# nl file.txt | sed "1a add text" 1 wtmp begins Mon Feb 24 14:26:08 2014add text 2 192.168.0.1 3 162.12.0.123 4 this is the last line
(2)第一行之前添加一行
[[email protected] ~]# 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行
[[email protected] ~]# 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行
[[email protected] ~]# sed -n "2,3p" file.txt 192.168.0.1162.12.0.123
這裡要提到的是,盡量使用-n,不然會出現這樣的結果
[[email protected] ~]# sed "2,3p" file.txt wtmp begins Mon Feb 24 14:26:08 2014192.168.0.1192.168.0.1162.12.0.123162.12.0.123this is the last line
(5)把168換成169
先看源檔案
[[email protected]lhost ~]# cat file.txt wtmp begins Mon Feb 24 14:26:08 2014192.168.0.1162.12.0.123this is the last line
處理後
[[email protected] ~]# sed "s/168/169/g" file.txt wtmp begins Mon Feb 24 14:26:08 2014192.169.0.1162.12.0.123this is the last line
(6)插入多行
[[email protected] ~]# nl file.txt | sed "2afirst\nsecond" file.txt wtmp begins Mon Feb 24 14:26:08 2014192.168.0.1firstsecond162.12.0.123this is the last line
(7)匹配資料,然後進行操作
只需要在上述的基礎上加上正則匹配
sed "/匹配的模式/處理的方式" file.txt
sed "/^root/d" file.txt 對開始有root的刪除
例如
匹配begin,並刪除改行
[[email protected] ~]# 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
[[email protected] ~]# 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">[[email protected] ~]# 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)直接修改檔案,切記不要修改系統檔案
[[email protected] ~]# sed -i "/begin/{s/24/25/g}" file.txt [[email protected] ~]# cat file.txt wtmp begins Mon Feb 25 14:26:08 2014192.168.0.1162.12.0.123this is the last line
三 、一個比較有趣的例子
如何替換\n也就是把所有的行都歸為一行
第一種方式
[[email protected] ~]# 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
第二種方式
[[email protected] ~]# 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
Linux Sed命令詳解+如何替換分行符號"\n"(很多面試問道)