您的位置:首页 > 其它

上古神器sed命令(中)

2017-04-25 21:06 211 查看

上古神器sed命令(中)

上古神器sed命令中

测试文档peopletxt
多个匹配

8将代替被匹配的变量

9如果使用正则表达式匹配项的时候使用了圆括号括了起来那么可以用123等来表示这些项难点

测试文档:(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
前面的匹配项可以被记为
\1
from
后面的匹配项可以被记为
\2


2,后面加下划线的
\1\t:\2
部分是替换的字符串,也就是只打印匹配出来的名字和国籍,中间用制表符和冒号隔开。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: