sed用法

基本用法:

sed,以行為單位進(jìn)行處理,可以直接將文件的內(nèi)容進(jìn)行增刪改查等操作

格式:
sed [選項(xiàng)] 參數(shù) 文件

格式 參數(shù) 解釋
-r 支持正則表達(dá)式
-i 直接修改文件內(nèi)容
-n 只打印匹配的行
a 在當(dāng)前行下面插入內(nèi)容
i 在當(dāng)前行上面插入內(nèi)容(直接修改,原文件也會(huì)修改)
c 把選定行改為新的文本(替換所在那行)
p 打印行(一般與-n一起使用,屏蔽默認(rèn)輸出,否則會(huì)出現(xiàn)兩行內(nèi)容)
s 替換指定字符

sed中編輯命令:

a 追加,向匹配行后面插入內(nèi)容
c 更改 ,更改匹配行的內(nèi)容
i 插入,向匹配行前插入內(nèi)容
d 刪除,刪除匹配行的內(nèi)容
s 替換,替換掉匹配的內(nèi)容
p 打印,打印出匹配的內(nèi)容,通常與-n選項(xiàng)合用
= 用來(lái)打印被匹配到行的行號(hào)
n 讀取下一行,遇到n時(shí)會(huì)自動(dòng)跳入下一行
r,w 讀寫編輯命令

示例:

新增:

sed -i '12 a this is test data‘ profile #profile的第12行后插入一行數(shù)據(jù)

sed -i '13 a export LD_LIBRARY_PATH=/a... \
export LD_LIBRARY_PATH=/b... \
export LD_LIBRARY_PATH=/c...' profile   #在profile的13行后插入三行數(shù)據(jù)

刪除:

sed -i 'd' profile      #刪除所有內(nèi)容行

sed -i '1,4d' profile        #刪除1-4行

sed -n '$=' profile        #輸出文件總行數(shù)

sed -n '2,6d' profile    #刪除2-6行

sed '/xml/d' profile    #刪除所有包含xml的行

sed '/xml/!d' profile    #刪除所有不包含xml的行,!取反

sed '$d'  profile    #刪除最后一行

sed '/^install/d'  profile    #刪除install開頭的行

sed '/^$/d'  profile    #刪除所以空行

修改:

sed 's/ww/web/' profile    #每行中第一個(gè)ww改成web

sed 's/ww/web/g' profile    #將所有的ww改成web

sed 's/ww/web/3' profile     #每行中第三個(gè)ww改成web

sed 's/xml//g' profile    #將所有的xml都置空(換成空)

sed 's#/bin/bash#/sbin/sh#g' profile    #包含/的替換,可以把格式換成#

sed '1,7s/^/#/'  profile  #第1~7行注釋掉

sed 's/^#//g'    profile    #將所有注釋去掉

查看:

sed -n '3,6p' profile    #打印3-6行

sed -n '1p;4p' profile    #打印第1和第4行

sed -n '3,+10p' profile    #打印第3行以及后面10行

sed -n '1~2p' profile    #打印奇數(shù)行

sed -n '2~2p' profile    #打印偶數(shù)行

sed -n '/root/p' profile    #打印包含root的行

sed -n '/bash$/p' profile    #打印bash結(jié)尾的行

sed -n '/^root/p'  profile     #輸出以root開頭的行
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容