sed 语法及使用示例

sed替换整行

sed '5s/^.*$/xxxxx/'  file
sed  -i -e'5c\want newstring'  file

 

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值