歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux服務器 >> linux-sed-非交互性文本流編輯器

linux-sed-非交互性文本流編輯器

日期:2017/3/2 16:45:21   编辑:Linux服務器

Sed是一個非交互性文本流編輯器。它編輯文件或標准輸入導出的文本拷貝

實例

1.行的匹配
[root@mypc /]# sed -n ‘2p’ /etc/passwd 打印出第2行
[root@mypc /]# sed -n ‘1,3p’ /etc/passwd 打印出第1到第3行
[root@mypc /]# sed -n ‘$p’ /etc/passwd 打印出最後一行
[root@mypc /]# sed -n ‘/user/’p /etc/passwd 打印出含有user的行
rpc:x:32:32:Portmapper RPC user:/:/sbin/nologin
rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin
[root@mypc /]# sed -n ‘/\$/’p /etc/passwd 打印出含有$元字符的行,$意為最後一行

2.插入文本和附加文本(插入新行)
[root@mypc /]# sed -n ‘/FTP/p’ /etc/passwd 打印出有FTP的行
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
[root@mypc /]# sed ‘/FTP/ a\ 456′ /etc/passwd 在含有FTP的行後面新插入一行,內容為456
[root@mypc /]# sed ‘/FTP/ i\ 123′ /etc/passwd在含有FTP的行前面新插入一行,內容為123
[root@mypc /]# sed ‘/FTP/ i\ “123″‘ /etc/passwd在含有FTP的行前面新插入一行,內容為”123″
[root@mypc /]# sed ‘5 a\ 123′ /etc/passwd 在第5行後插入一新行,內容為123
[root@mypc /]# sed ‘5 i\ “12345″‘ /etc/passwd 在第5行前插入一新行,內容為”12345″

3.刪除文本
[root@mypc /]# sed ‘1d’ /etc/passwd 刪除第1行
[root@mypc /]# sed ‘1,3d’ /etc/passwd 刪除第1至3行
[root@mypc /]# sed ‘/user/d’ /etc/passwd 刪除帶有user的行

4. 替換文本,替換命令用替換模式替換指定模式,格式為:
[ a d d r e s s [,address]] s/ pattern-to-find /replacement-pattern/[g p w n]
[root@mypc /]# sed ’s/user/USER/’ /etc/passwd 將第1個user替換成USER,g表明全局替換
[root@mypc /]# sed ’s/user/USER/g’ /etc/passwd 將所有user替換成USER
[root@mypc /]# sed ’s/user/#user/’ /etc/passwd 將第1個user替換成#user,如用於屏蔽作用
[root@mypc /]# sed ’s/user//’ /etc/passwd 將第1個user替換成空
[root@mypc /]# sed ’s/user/&11111111111111/’ /etc/passwd 如果要附加或修改一個很長的字符串,可以使用( &)命令,
&命令保存發現模式以便重新調用它,然後把它放在替換字符串裡面,這裡是把&放前面
[root@mypc /]# sed ’s/user/11111111111111&/’ /etc/passwd 這裡是將&放後面

5. 快速一行命令
下面是一些一行命令集。([ ]表示空格,[ ]表示t a b鍵)
‘s / \ . $ / / g’ 刪除以句點結尾行
‘-e /abcd/d’ 刪除包含a b c d的行
‘s / [ ] [ ] [ ] * / [ ] / g’ 刪除一個以上空格,用一個空格代替
‘s / ^ [ ] [ ] * / / g’ 刪除行首空格
‘s / \ . [ ] [ ] * / [ ] / g’ 刪除句點後跟兩個或更多空格,代之以一個空格
‘/ ^ $ / d’ 刪除空行
‘s / ^ . / / g’ 刪除第一個字符
‘s /COL \ ( . . . \ ) / / g’ 刪除緊跟C O L的後三個字母
‘s / ^ \ / / / g’ 從路徑中刪除第一個\
‘s / [ ] / [ ] / / g’ 刪除所有空格並用t a b鍵替代
‘S / ^ [ ] / / g’ 刪除行首所有t a b鍵
‘s / [ ] * / / g’ 刪除所有t a b鍵
如果使用s e d對文件進行過濾,最好將問題分成幾步,分步執行,且邊執行邊測試結果

Copyright © Linux教程網 All Rights Reserved