linux命令 sed 有的功能有,Linux命令:sed简介
sed是一種在線行編輯器,一次處理一行。工作時,把當(dāng)前處理的行放到“模式空間”中進行編輯,編輯完成后把內(nèi)容輸送至屏幕。
語法:sed [OPTION]…{script}…[input file]
選項:
-r:支持正則表達式
-n:靜默模式,不顯示內(nèi)容
-e: script1 -e script2 -e script3:指定多腳本運行
-f /path/to/script_file:從指定的文件中讀取腳本并運行
-i: 直接修改源文件
命令:
d: 刪除模式空間中的行;
=:顯示行號;
a \text:附加text
i \text:插入text,支持\n實現(xiàn)多行插入;
c \text:用text替換匹配到的行;
p: 打印模式空間中的行;
s/regexp/replacement/:替換由regexp所匹配到的內(nèi)容為replacement;
g: 全局替換;
w /path/to/somefile:把指定的內(nèi)容另存至/path/to/somefile路徑所指定的文件中;
r /path/from/somefile:在文件的指定位置插入另一個文件的所有內(nèi)容,完成文件合并
正則:
字符匹配:., [], [^]
次數(shù)匹配:*, \?, \+, \{m,n\}, \{n\}
位置錨定:^, $, \
分組及引用:\(\), \1, \2, ...
多選一:a|b|c
定界:
#: 指定行;
$: 最后一行;
/regexp/:任何能夠被regexp所匹配到的行;
\%regexp%:同上,只不過換作%為regexp邊界符;
/regexp/| :
\%regexp%| :匹配時忽略字符大小寫;
startline,endline:
#,/regexp/:從#行開始,到第一次被/regexp/所匹配到的行結(jié)束,中間的所有行;
#,#
/regexp1/,/regexp2/:從第一次被/regexp1/匹配到的行開始,到第一次被/regexp2/匹配到的行結(jié)束,中間的所有行;
#,+n:從#行開始,一直到向下的n行;
first~step:指定起始行,以及步長;
1~2,2~2
高級命令:
h:用模式空間中的內(nèi)容覆蓋保持空間的內(nèi)容;
H:把模式空間中的內(nèi)容追加至保持空間中內(nèi)容的后面;
g:從保持空間中取到其內(nèi)容,并將其覆蓋模式空間中的內(nèi)容;
G:從保持空間中取到其內(nèi)容,并將其追加在模式空間中的內(nèi)容的后面;
x:把保持空間和模式空間中的進行交換;
n:讀取匹配到的行的下一行至模式空間;(會覆蓋模式空間中的原有內(nèi)容);
N:讀取匹配到的行的下一行至模式空間,追加在模式空間中原有內(nèi)容的后面;
d:刪除模式空間中的內(nèi)容;
D:刪除多行模式空間中的首行;
注意:命令功能可使用!取反;分號可用于分隔腳本;
練習(xí):
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.打印奇數(shù)行
[root@localhost ~]# sed -n '1~2p' file
1,this is my test line
3,hello
5,my
7,you
總結(jié)
以上是生活随笔為你收集整理的linux命令 sed 有的功能有,Linux命令:sed简介的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。