【问题标题】:how to ignore line break in text search?如何忽略文本搜索中的换行符?
【发布时间】:2011-07-07 09:21:20
【问题描述】:

使用sed,我想搜索一个字符串并将其替换为maven pom.xml中的其他字符串

<groupId>com.abc</groupId>
<version>3.1</version>

<groupId>com.abc</groupId>
<version>4.1</version>

我写的

find . -name 'pom.xml' -type f -exec sed -i "s!"<groupId>com.abc</groupId>\n
<version>3.1</version>"!"<groupId>com.abc</groupId>\n    <version>4.1</version>!" '{}' \; 

但它永远不会起作用!

【问题讨论】:

  • sed 不是多行编辑的最佳工具。尝试改用perl

标签: xml maven sed replace


【解决方案1】:

您需要使用N 命令读取下一行。查看出色的 Sed and Awk 书籍,了解有关处理多行模式空间的更多详细信息。有点繁琐。

将此 sed 命令保存到文件,例如 cmd.txt

/<groupId>com.abc<\/groupId>/{
N
s/<groupId>com.abc<\/groupId>\n<version>3.1<\/version>/<groupId>com.abc<\/groupId>\n<version>4.1<\/version>/
}

然后运行:

$ sed -f cmd.txt pom.xml

【讨论】:

    【解决方案2】:

    不要为此使用 sed。换行符是 sed 的一部分。这是 xslt 的工作。

    以下代码 sn-p 是从http://chrisdail.com/2009/05/17/changing-maven-pom-versions-with-groovy-and-xslt/借用和调整的

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
        <xsl:template match="@*|node()">
            <xsl:copy>
                <xsl:apply-templates select="@*|node()"/>
            </xsl:copy>
        </xsl:template> 
        <xsl:template match="version[../groupId='com.abc']">
            <version>4.1</version>
        </xsl:template>
    </xsl:stylesheet>
    

    只需执行 xsltproc thisfile.xsl pom.xml

    【讨论】:

      【解决方案3】:

      试试这个...希望它有帮助。

      sed -e 's/3.1/4.1/g' pom.xml > pom1.xml
      

      【讨论】:

      • 不能使用这个,因为版本 3.1 的依赖项不止一个。还需要搜索组 id
      • 在这种情况下,您将不得不像@mouviviel 提到的那样使用 Perl 来进行多模式的多行搜索。
      猜你喜欢
      • 2013-03-08
      • 2019-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-12
      • 2012-07-14
      • 1970-01-01
      相关资源
      最近更新 更多