sed是一種在線行編輯器,一次處理一行。工作時,把當前處理的行放到“模式空間”中進行編輯,編輯完成後把內容輸送至屏幕。
語法:sed [OPTION]…{script}…[input file]
選項:
-r:支持正則表達式
-n:靜默模式,不顯示內容
-e: script1 -e script2 -e script3:指定多腳本運行
-f /path/to/script_file:從指定的文件中讀取腳本並運行
-i: 直接修改源文件
命令:
d: 刪除模式空間中的行;
=:顯示行號;
a \text:附加text
i \text:插入text,支持\n實現多行插入;
c \text:用text替換匹配到的行;
p: 打印模式空間中的行;
s/regexp/replacement/:替換由regexp所匹配到的內容爲replacement;
g: 全局替換;
w /path/to/somefile:把指定的內容另存至/path/to/somefile路徑所指定的文件中;
r /path/from/somefile:在文件的指定位置插入另一個文件的所有內容,完成文件合併
正則:
字符匹配:., [], [^]
次數匹配:*, \?, \+, \{m,n\}, \{n\}
位置錨定:^, $, \<, \>
分組及引用:\(\), \1, \2, ...
多選一:a|b|c
定界:
#: 指定行;
$: 最後一行;
/regexp/:任何能夠被regexp所匹配到的行;
\%regexp%:同上,只不過換作%爲regexp邊界符;
/regexp/| :
\%regexp%| :匹配時忽略字符大小寫;
startline,endline:
#,/regexp/:從#行開始,到第一次被/regexp/所匹配到的行結束,中間的所有行;
#,#
/regexp1/,/regexp2/:從第一次被/regexp1/匹配到的行開始,到第一次被/regexp2/匹配到的行結束,中間的所有行;
#,+n:從#行開始,一直到向下的n行;
first~step:指定起始行,以及步長;
1~2,2~2
高級命令:
h:用模式空間中的內容覆蓋保持空間的內容;
H:把模式空間中的內容追加至保持空間中內容的後面;
g:從保持空間中取到其內容,並將其覆蓋模式空間中的內容;
G:從保持空間中取到其內容,並將其追加在模式空間中的內容的後面;
x:把保持空間和模式空間中的進行交換;
n:讀取匹配到的行的下一行至模式空間;(會覆蓋模式空間中的原有內容);
N:讀取匹配到的行的下一行至模式空間,追加在模式空間中原有內容的後面;
d:刪除模式空間中的內容;
D:刪除多行模式空間中的首行;
注意:命令功能可使用!取反;分號可用於分隔腳本;
練習:
1.刪除/root/file文件中所有行的行首的空白字符
[root@localhost ~]# cat file && cat file |wc -l
aaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbb
cccccccccccccccc
2. 刪除/etc/fstab文件中所有以#開頭,後跟至少一個空白字符的行的行首的#和空白字符
[root@localhost ~]# sed 's/^#[[:space:]]\+//' /etc/fstab
#
/etc/fstab
Created by anaconda on Wed Aug 26 23:57:24 2015
#
Accessible filesystems, by reference, are maintained under '/dev/disk'
See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/VolGroup-lv_root / ext4 defaults 1 1
UUID=ccfe9f33-b5da-48b1-821b-b3bec206147b /boot ext4 defaults 1 2
/dev/mapper/VolGroup-lv_swap swap swap defaults 0 0
tmpfs /dev/shm tmpfs defaults 0 0
devpts /dev/pts devpts gid=5,mode=620 0 0
sysfs /sys sysfs defaults 0 0
proc /proc proc defaults 0 0
3. 只查看/etc/fstab文件的第1行到第5行
[root@localhost ~]# sed -n '1,5p' /etc/fstab
#
# /etc/fstab
# Created by anaconda on Wed Aug 26 23:57:24 2015
#
4.刪除文件中包含“my”的行到包含“you”的行之間的行
[root@localhost ~]# cat file
this is my test line
how are you
hello
how are you tom
my
aaaaaaaaaaaaa
you
[root@localhost ~]# sed '/my/,/you/d' file
hello
how are you tom
5.查詢包含“you”的所有行
[root@localhost ~]# sed -n '/you/p' file
how are you
how are you tom
you
6.在文件中每行後面添加空行
[root@localhost ~]# sed 'G' file
this is my test line
how are you
hello
how are you tom
my
aaaaaaaaaaaaa
you
7. 保證指定的文件每一行後方有且只有一個空白行
[root@localhost ~]# sed '/^$/d;G' file
this is my test line
how are you
hello
how are you tom
my
aaaaaaaaaaaaa
you
8.打印奇數行
[root@localhost ~]# sed -n '1~2p' file
1,this is my test line
3,hello
5,my
7,you