如何通过SED更改单词的第一部分?

时间:2017-02-08 19:17:47

标签: sed terminal

我只是想知道它为什么不起作用:

原创

red wagon logon
Blue wagon logon
Black wagon logon
red wagon logon
red wagon logon
red walking 43 logon
red wagon logon 89
Pink wagon logon 110
red wagon logon
red wagon logon
green wagon logon

此命令效果很好:sed 's:wa\(gon\):poly\1:' wagon.txt

结果

red polygon logon
Blue polygon logon
Black polygon logon
red polygon logon
red polygon logon
red walking 43 logon
red polygon logon 89
Pink polygon logon 110
red polygon logon
red polygon logon
green polygon logon

现在我想要wapoly,但是打印polywa为什么?

命令:sed 's:\(wa\)gon:poly\1:' wagon.txt

red polywa logon
Blue polywa logon
Black polywa logon
red polywa logon
red polywa logon
red walking 43 logon
red polywa logon 89
Pink polywa logon 110
red polywa logon
red polywa logon
green polywa logon

谢谢

1 个答案:

答案 0 :(得分:1)

将捕获组从gon更改为wa,并将替换部分构建为\1,其中wa附加poly

sed 's:\(wa\)gon:\1poly:' file
red wapoly logon
Blue wapoly logon
Black wapoly logon
red wapoly logon
red wapoly logon
red walking 43 logon
red wapoly logon 89
Pink wapoly logon 110
red wapoly logon
red wapoly logon
green wapoly logon

\1\2是替换部分中regex的捕获组,例如,在s:\(wa\)gon:\1poly:行中捕获的部分wa \1以后可以在替换部分中用\1poly输出wapoly

为了使用相同的示例\2来演示s:\(wa\)g\(on\):\1poly\2:的用法,现在,\1代表的已捕获的群组1已wa,已捕获的群组2 {{ 1}}有\2,现在构造的字符串on将为\1poly\2

wapolyon