【问题标题】:Replacing multiple lines in awk (or something)替换 awk 中的多行(或其他内容)
【发布时间】:2023-03-25 04:46:01
【问题描述】:

我一直在尝试使用 SED 完成以下任务,但由于 SED 是基于行的,我恐怕无法做到:

sed -ri 's/(<li>\n\s+<a href="#introduction")/<li><div class="toc-group">Topics<\/div><\/li>\1/' index.php

这应该不会改变:

          <li>
        <a href="#introduction" class="toc-h1 toc-link" data-title="Introduction">Introduction</a>

进入这个

<li><div class="toc-group">Topics<\/div></li><li>
        <a href="#introduction" class="toc-h1 toc-link" data-title="Introduction">Introduction</a>

基本上是穷人的“在特定位置添加一行”。不幸的是\n 没有按预期工作。我认为 AWK 可以做到这一点,但 SED 是我曾经使用过的唯一工具,而且我对 AWK 一无所知,所以请帮助我解决问题。

仅供参考 需要在文档的不同部分添加多个项目,因此我需要一种解决方案,允许我选择代码的一部分,然后在其前面添加。它将在 bash 脚本中用于自动化。

【问题讨论】:

  • 用 sed 解析 html 是一个非常糟糕的主意。添加更多上下文数据(当前节点的父节点)

标签: regex shell awk sed replace


【解决方案1】:

我刚刚开始学习 sed 和 awk,但是这种语法似乎在文本之间添加了行。

 sed 's/<li>/<li><div class="toc-group">\n/g' x.txt

输出:

<li><div class="toc-group">
<a href="#introduction" class="toc-h1 toc-link" data-
title="Introduction">Introduction</a>

我只放了你的 index.php 的一个子集来减少示例的长度。此处的输出显示 a href=... 行的拆分,但当我运行脚本时它是一行,因此这只是本文中的一个编辑问题。

【讨论】:

    【解决方案2】:

    perl 单行代码怎么样:

    perl -0777 -ne 's/(<li>\n\s+<a href="#introduction")/<li><div class="toc-group">Topics<\/div><\/li>$1/; print' inputfile
    

    输出:

          <li><div class="toc-group">Topics</div></li><li>
        <a href="#introduction" class="toc-h1 toc-link" data-title="Introduction">Introduction</a>
    

    【讨论】:

    • 感谢您提供解决方案而不是说教:)
    猜你喜欢
    • 2011-01-23
    • 2012-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多