替换文件中的所有字符串,在替换中使用通配符

用户2010496

我在bash中使用sed尝试替换所有匹配的字符串:

compile 'com.test.*:*'

和:

compile 'com.test.*:+'

其中*是通配符。

我的文件看起来像这样,叫做moo.txt:

compile 'com.test.common:4.0.1'
compile 'com.test.streaming:5.0.10'
compile 'com.test.ui:1.0.7'

我希望它看起来像这样:

compile 'com.test.common:+'
compile 'com.test.streaming:+'
compile 'com.test.ui:+'

我试图像这样使用sed:

sed -i -- "s/compile \'com.test.*:.*\'/compile \'com.test.*:+\'/g" moo.txt

但这使文件看起来像:

compile 'com.test.*:+'
compile 'com.test.*:+'
compile 'com.test.*:+'

有什么想法如何在替代字段中正确使用通配符?

fedorqui'停止伤害'

您要匹配的东西,com.test但不能正确地打印回来。

因此,您确实在匹配某些内容,只是您没有将其打印回来。相反,您正在打印文字.*

sed "s/compile \'com.test.*:.*\'/compile \'com.test.*:+\'/g"
#                        ^^                        ^^
#                match this                  print back? NO

为此,捕获图案并使用向后引用将其打印回去。

sed -E "s/compile 'com.test(.*):.*'/compile 'com.test\1:+'/g"
#                          ^^^^                      ^^
#                    catch this             print back! now YES!

看到我们重复太多“编译...”了吗?这意味着我们可以将捕获扩展到该行的开始,因为反向引用会将所有捕获打印回去:

sed -E "s/^(compile 'com.test.*):.*'/\1:+'/g"
#          ^^^^^^^^^^^^^^^^^^^^^     ^^
#           capture all of this      print it back

请注意的用法,-E以允许sed带有的捕获组(...)如果我们不使用-E,我们应该做\(...\)

还要注意,您在转义单引号,但由于在双引号内,因此没有必要。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章