sed command

簡介

sed 是一種在線編輯器,它一次處理一行內容。處理時,把當前處理的行存儲在臨時緩衝區中,稱爲“模式空間”(pattern space),接着用sed命令處理緩衝區中的內容,處理完成後,把緩衝區的內容送往屏幕。接着處理下一行,這樣不斷重複,直到文件末尾。文件內容並沒有 改變,除非你使用重定向存儲輸出。Sed主要用來自動編輯一個或多個文件;簡化對文件的反覆操作;編寫轉換程序等

[root@localhost~]# sed [-nefr] [動作]
選項與參數:
-n :使用安靜(silent)模式。在一般 sed 的用法中,所有來自 STDIN 的數據一般都會被列出到終端上。但如果加上 -n 參數後,則只有經過sed 特殊處理的那一行(或者動作)纔會被列出來。
-e :直接在命令列模式上進行 sed 的動作編輯;
-f :直接將 sed 的動作寫在一個文件內, -f filename 則可以運行 filename 內的 sed 動作;
-r :sed 的動作支持的是延伸型正規表示法的語法。(默認是基礎正規表示法語法)
-i :直接修改讀取的文件內容,而不是輸出到終端。

動作說明: [n1[,n2]]function
n1, n2 :不見得會存在,一般代表『選擇進行動作的行數』,舉例來說,如果我的動作是需要在 10 到 20 行之間進行的,則『 10,20[動作行爲] 』

function:
a :新增, a 的後面可以接字串,而這些字串會在新的一行出現(目前的下一行)~
c :取代, c 的後面可以接字串,這些字串可以取代 n1,n2 之間的行!
d :刪除,因爲是刪除啊,所以 d 後面通常不接任何咚咚;
i :插入, i 的後面可以接字串,而這些字串會在新的一行出現(目前的上一行);
p :列印,亦即將某個選擇的數據印出。通常 p 會與參數 sed -n 一起運行~
s :取代,可以直接進行取代的工作哩!通常這個 s 的動作可以搭配正規表示法!例如 1,20s/old/new/g 就是啦!

新增/刪除
刪除2~5行

[root@localhost ~]# nl /etc/passwd|sed '2,5d'
     1  root:x:0:0:root:/root:/bin/bash
     6  sync:x:5:0:sync:/sbin:/bin/sync
     7  shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
     8  halt:x:7:0:halt:/sbin:/sbin/halt

要刪除第 3 到最後一行

nl /etc/passwd | sed '3,$d'

在第二行後(亦即是加在第三行)加上『hello world』字樣!

[root@localhost ~]# nl /etc/passwd|sed '2a hello world'
     1  root:x:0:0:root:/root:/bin/bash
     2  bin:x:1:1:bin:/bin:/sbin/nologin
hello world
     3  daemon:x:2:2:daemon:/sbin:/sbin/nologin

那如果是要在第二行前

nl /etc/passwd | sed '2i drink tea' 

以行爲單位的替換與顯示
將第2-5行的內容取代成爲『No 2-5 number』

[root@localhost ~]# nl /etc/passwd|sed '2,5c No 2-5 number'
     1  root:x:0:0:root:/root:/bin/bash
No 2-5 number
     6  sync:x:5:0:sync:/sbin:/bin/sync

數據的搜尋並顯示
搜索 /etc/passwd有root關鍵字的行

nl /etc/passwd | sed '/root/p'
 root:x:0:0:root:/root:/bin/bash
 root:x:0:0:root:/root:/bin/bash
 daemon:x:1:1:daemon:/usr/sbin:/bin/sh
 bin:x:2:2:bin:/bin:/bin/sh
 sys:x:3:3:sys:/dev:/bin/sh
 sync:x:4:65534:sync:/bin:/bin/sync

數據的搜尋並刪除
刪除/etc/passwd所有包含root的行,其他行輸出

nl /etc/passwd | sed  '/root/d'
2  daemon:x:1:1:daemon:/usr/sbin:/bin/sh
3  bin:x:2:2:bin:/bin:/bin/sh
第一行的匹配root已經刪除了

數據的搜尋並執行命令
找到匹配模式eastern的行後,搜索/etc/passwd,找到root對應的行,執行後面花括號中的一組命令,每個命令之間用分號分隔,這裏把bash替換爲blueshell,再輸出這行:

nl /etc/passwd | sed -n '/root/{s/bash/blueshell/;p}'
 1  root:x:0:0:root:/root:/bin/blueshell

如果只替換/etc/passwd的第一個bash關鍵字爲blueshell,就退出

nl /etc/passwd | sed -n '/bash/{s/bash/blueshell/;p;q}'    
1  root:x:0:0:root:/root:/bin/blueshell

修改文件

[root@localhost ~]# sed -i s#SELINUX=enforcing#SELINUX=disabled#g /etc/selinux/config 
[root@localhost ~]# grep "disabled" /etc/selinux/config 
#     disabled - No SELinux policy is loaded.
SELINUX=disabled
發佈了85 篇原創文章 · 獲贊 13 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章