上古神器sed命令(中)

上古神器sed命令(中)

测试文档:(people.txt)

Jack    is 18-year old, he comes from US.
Mike    is 16-year old, he comes from Canada.
Chen    is 21-year old, he comes from China.
Lau     is 18-year old, he comes from HongKong.
Michael is 20-year old, he comes from UK.
Phoebe  is 18-year old, she comes from Australie.
多个匹配

7,将”-year”改成” years”,并且将第3行以后的最后一个任意字符去掉:

sed 's/-year/ years/; 3,$s/.$//' people.txt 
Jack    is 18 years old, he comes from US.
Mike    is 16 years old, he comes from Canada.
Chen    is 21 years old, he comes from China
Lau     is 18 years old, he comes from HongKong
Michael is 20 years old, he comes from UK
Phoebe  is 18 years old, she comes from Australie

注释:3,$s/.$//
分步看:
(1)s/.$//是个整体,看作s/ (中间的为一) / (中间的为二)/
——————————-一里面是.$行尾匹配任意一个字符
——————————-二里面什么都没有,用二去替换一
(2)3,$ 从第3行到最后

以上命令等价于:

sed -e 's/-year/ years/' -e '3,$s/.$//' people.txt

注意:在单引号里面,元义字符可以直接使用,如果要去掉元义则要在前面加\ 在双引号里面,sed的命令要使用元义,则需要加\ , 而命令的正则表达式要使用元义直接使用就行。

8,将&代替被匹配的变量:
sed "s/is/[&]/" people.txt
Jack    [is] 18-year old, he comes from US.
Mike    [is] 16-year old, he comes from Canada.
Chen    [is] 21-year old, he comes from China.
Lau     [is] 18-year old, he comes from HongKong.
Michael [is] 20-year old, he comes from UK.
Phoebe  [is] 18-year old, she comes from Australie.

意思是==>:将文本中每一行出现的第一个is的左右两边加上[ ]

9,如果使用正则表达式匹配项的时候使用了圆括号括了起来,那么可以用\1,\2,\3……等来表示这些项:(难点)
sed "s/\(^.*\)\tis.*from \(.*\)./\1\t:\2/g" people.txt
Jack    :US
Mike    :Canada
Chen    :China
Lau     :HongKong
Michael :UK
Phoebe  :Australie

注释:分步看
(1)s/ (中间的为一)/ (中间的为二) /g 用二替换一
二现在是\1\t:\2表示输出圆括号内\1\2
(2)\(^.*\)\tis.*from \(.*\). 去掉转义符号(^.*)\tis.*from (.*). 那么第一个圆括号匹配的是\1,第二个匹配的是\2,两个圆括号之间的字符是舍弃掉的(每一行都按照这个规则舍弃)

分解一下:
1,其中加粗的\(^.*\)\tis.*from \(.*\).是正则表达式,简化一下是(^.*)\tis.*from (.*). 在这个表达式中,制表符\t前面的匹配项可以被记为\1from后面的匹配项可以被记为\2
2,后面加下划线的\1\t:\2部分是替换的字符串,也就是只打印匹配出来的名字和国籍,中间用制表符和冒号隔开。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值