sed 的使用(一) -- s參數/替換

1. sed的語法命令

[address] command 或者

address {command

command

command

}

如果沒有指定地址,將命令運用於匹配的每一行

1abcd

TS 2abcd abcd

3abcd

ps 10

vs 12

TE 4abcd

 

6abcd

7abcd

cd---ab

cd--ab

See Section 1.4

See Section 12.44

Class:Group

Contrator:Employee

 

例:

sed -n '/^TS/ s/abcd/efgh/p' test

=> TS 2efgh abcd

 

sed -n '/^TS/ s/abcd/efgh/2p' test #加數字可以指定本行第n次匹配

=> TS 2abcd efgh

 

sed -n '/^TS/ s/abcd/efgh/pg' test #本行全匹配

=> TS 2efgh efgh

 

sed -n '/^TS/! s/abcd/efgh/pg' test #地址後加!應用於不匹配該行的所有行

=>

1efgh

3efgh

TE 4efgh

6efgh

7efgh

 

sed -n '/^TS/, /^TE/ s/abcd/efgh/pg' test #匹配從以TS開頭的行到以TE開頭的行

=>

TS 2efgh efgh

3efgh

TE 4efgh

 

sed -n '/^TS/, /^TE/ s/abcd/efgh/wha.txt' test #將sed的結果重定向到文件ha.txt

cat ha.txt

=>

TS 2efgh efgh

3efgh

TE 4efgh

 

2. sed的分組命令

sed '/^TS/,/^TE/ {s/abcd/efgh/;/^ps/d}' test

 

3. & 在replacement中, 表示pattern的內容

sed 's/See Section [0-9][1-9]*/.[0-9][1-9]*/(&)/' test

=>

(See Section 1.4)

(See Section 12.44)

 

4. 在sed中,轉義的括號括住正則表達式的任意部分(pattern),可以在replacement部分中回調

sed 's//(.*/):/(.*/)//2:/1/' test

=>

Group:Class

Employee:Contrator

 

5. 如果替換的部分包括特殊符號,如/,可以用另外的符號來替代sed中的/

    sed引用外部變量時,要用''括起來。

item=KERNEL

value=/home/yazi/default

 

sed -n '/^'$item'/p' $profile
KERNEL=<kernel path>

現在要把=的後半部分替換成value的值

 

sed -n '/^'$item'/s&/(.*/)=.*&/1='$value'&p' $profile

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章