linux - 使用 Sed 替换下一行但保留空格

标签 linux sed

我在这里使用这个答案:https://stackoverflow.com/a/18622953/1797263替换 pom.xml 文件中的版本。我遇到的问题是它正在删除前面的空格,而我想保留前面的空格。空白可以是 2 或 3 个制表符或空格,具体取决于开发人员如何格式化文件。

这是一个例子:

        <dependency>
            <groupId>GROUP</groupId>
            <artifactId>ARTIFACT</artifactId>
            <version>OLD_VERSION</version>
        </dependency>

我的命令:sed -i '/<artifactId>ARTIFACT<\/artifactId>/!b;n;c<version>NEW_VERSION</version>' pom.xml

我的输出:

        <dependency>
            <groupId>GROUP</groupId>
            <artifactId>ARTIFACT</artifactId>
<version>NEW_VERSION</version>
        </dependency>

这是我希望的替代品:

        <dependency>
            <groupId>GROUP</groupId>
            <artifactId>ARTIFACT</artifactId>
            <version>NEW_VERSION</version>
        </dependency>

我通读了 GNU Sed 手册,但找不到任何有帮助的内容。

最佳答案

使用正确的解析器:

xmlstarlet edit -L -u '/dependency/version' -v NEW_VERSION file.xml

 输出

<?xml version="1.0"?>
<dependency>
  <groupId>GROUP</groupId>
  <artifactId>ARTIFACT</artifactId>
  <version>NEW_VERSION</version>
</dependency>

不要使用正则表达式解析 XML/HTML,使用适当的 XML/HTML 解析器和强大的 查询。

理论:

According to the compiling theory, XML/HTML can't be parsed using regex based on finite state machine. Due to hierarchical construction of XML/HTML you need to use a pushdown automaton and manipulate LALR grammar using tool like YACC.

realLife©®™ 日常工具 :

您可以使用以下其中一项:

xmllint通常默认与 libxml2、xpath1 一起安装(检查 my wrapper 以换行符分隔输出

xmlstarlet可以编辑、选择、转换...默认不安装,xpath1

xpath通过 perl 的模块 XML::XPath, xpath1 安装

xidel xpath3

saxon-lint我自己的项目,@Michael Kay 的 Saxon-HE Java 库 xpath3 的包装器

或者你可以使用高级语言和适当的库,我认为:

lxml (从 lxml 导入 etree)

XML::LibXML , XML::XPath , XML::Twig::XPath , HTML::TreeBuilder::XPath

, check this example

DOMXpathcheck this example

<小时/>

检查:Using regular expressions with HTML tags

enter image description here

关于linux - 使用 Sed 替换下一行但保留空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59470854/

相关文章:

linux - smbclient put 期间的进度条

linux - 禁用 Linux 调度程序来测量特定机器代码指令的功耗

linux - Linux/X11下如何隐藏鼠标指针?

linux - 无法从日志文件中提取准确的键值对

awk - 在 awk 语句中使用 sed

bash - 当另一个变量中已知关联的子字符串时,确定一个变量中的子字符串

ubuntu - 如何使用存储在变量中的 sed 删除 ubuntu 中的一行?

python - 没有名为 libxml2 的模块 - Linux Mint Rafaela (Ubuntu 14.04)

linux - 为 map 服务器安装 gd 库时出错

regex - 如何在shell脚本中使用 'sed'替换文件中的一行