首页 > 解决方案 > SED 不使用复杂的正则表达式更新

问题描述

作为构建过程的一部分,我正在尝试自动更新文件中的版本号。我可以使以下工作,但仅适用于每个主要/次要/修复位置中具有单个数字的版本号。

sed -i 's/version="[0-9]\.[0-9]\.[0-9]"/version="2.4.567"/g' projectConfig.xml

我尝试了一个更复杂的正则表达式模式,它在 MS Regular Xpression Tool 中工作,但在运行 sed 时不匹配。

sed -i 's/version="\b\d{1,3}\.\d{1,3}\.\d{1,3}\b"/version="2.4.567"/g' projectConfig.xml

示例输入:

This is a file at version="2.1.245" and it consists of much more text.

期望的输出

This is a file at version="2.4.567" and it consists of much more text.

我觉得我缺少一些东西。

标签: regexsed

解决方案


有3个问题:

要启用量词 ( {}),sed您需要-E/--regexp-extended开关(或使用\{\},请参阅http://www.gnu.org/software/sed/manual/html_node/Regular-Expressions.html#Regular-Expressions

字符集简写\d[[:digit:]].sed

您的输入未引用".

sed 's/version=\b[[:digit:]]\{1,3\}\.[[:digit:]]\{1,3\}\.[[:digit:]]\{1,3\}\b/version="2.4.567"/g' \
    <<< "This is a file at version=2.1.245 and it consists of much more text."

为了保持更便携,您可能需要使用--posix开关(需要移除\b):

sed --posix 's/version=[[:digit:]]\{1,3\}\.[[:digit:]]\{1,3\}\.[[:digit:]]\{1,3\}/version="2.4.567"/g' \
   <<< "This is a file at version=2.1.245 and it consists of much more text."

推荐阅读