现在的位置: 首页 > 综合 > 正文

sed 的使用(一) — s参数/替换

2013年08月19日 ⁄ 综合 ⁄ 共 1107字 ⁄ 字号 评论关闭

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

 

 

 

 

 

 

 

抱歉!评论已关闭.