【问题标题】:MacOs sed replace does not work for html fileMacOs sed 替换不适用于 html 文件
【发布时间】:2020-11-18 01:15:24
【问题描述】:

我正在尝试在我的文档中添加 <h4> 标记 <button class="collapse"> 并在 </h4> 标记之后添加结束标记 </button>

我的示例文档如下所示:

<h4 id="id1">Some text.<br />
</h4>
<div class="content">
<p>Content.</p>
</div>

<h4 id="id2">Some text 2.<br />
</h4>
<div class="content">
<p>Content.</p>
</div>

<h4 id="id3">Some text 3.<br />
</h4>
<div class="content">
<p>Content.</p>
</div>

<h4 id="id4">Some text 4.<br />
</h4>
<div class="content">
<p>Content.</p>
</div>

我想要实现的是:

<button class="collapse"><h4 id="id1">Some text.<br />
</h4></button>
<div class="content">
<p>Content.</p>
</div>

<button class="collapse"><h4 id="id2">Some text 2.<br />
</h4></button>
<div class="content">
<p>Content.</p>
</div>

<button class="collapse"><h4 id="id3">Some text 3.<br />
</h4></button>
<div class="content">
<p>Content.</p>
</div>

<button class="collapse"><h4 id="id4">Some text 4.<br />
</h4></button>
<div class="content">
<p>Content.</p>
</div>

我尝试的是这样的:sed -E -i -e 's/(\&lt;h4\w*.*)(\n)(\&lt;\/h4\&gt;)/\&lt;button\ class\=\"collapse\"\&gt;\1\2\n\3\&lt;\/button\&gt;/' index.html

虽然它不起作用,它不会改变任何东西,类似的 sed 和类似的正则表达式适用于 markdown 文件,但我无法让它与 html 文件一起使用。

我还尝试在 Atom 编辑器中查找和替换,使用:(&lt;h4\w*.*)(\n)(&lt;/h4&gt;) 作为正则表达式,&lt;button class="collapse"&gt;$1$2$3&lt;/button&gt; 作为替换,这绝对完美。

我的错误是什么?可能是换行符吗?我将如何在 MacO 上使用 sed 来实现我所需要的,我正在使用 bash。

非常感谢,希望有任何帮助

【问题讨论】:

  • 你认为\w*在做什么?
  • 请注意,如果没有更多的 sed 编程,sed 是严格面向行的。
  • \w 是一个 GNU sed 扩展。我怀疑它可以在 MacOS sed 上运行。
  • @glennjackman 嗨,以我有限的正则表达式经验,我想它应该找到任何单词,并且 . 应该包括任何其他字符,直到下一组“开始”,我不是 100 %肯定寿(初学者)。我也意识到 sed 是严格面向行的,因此我尝试使用换行符,这不是正确的方法吗?谢谢
  • @M.NejatAydin 谢谢,我试过这个例子,它工作了:cat test.md | sed -E 's/(#### )(\w*.*)(.\ \\)/\1, \2\3, /' 所以我想,\w 也应该在 MacOS 上工作,不过我可能弄错了。

标签: html bash sed replace


【解决方案1】:
sed -e 's/^<h4/<button class="collapse">&/' -e 's:</h4>:&</button>:' infile

【讨论】:

  • 谢谢,效果很好。我了解第二部分,但请您解释一下这部分:'s/^&lt;h4/&lt;button class="collapse"&gt;&amp;/' 吗?我不明白如何在不包含
  • 你明白了,&amp; 被匹配的正则表达式替换 - 在这种情况下,&lt;h4(无锚点 ^);第二部分还有一个&amp;
  • this doc中搜索&amp;
猜你喜欢
  • 2021-05-21
  • 1970-01-01
  • 2018-08-29
  • 2018-12-26
  • 2016-02-28
  • 2017-11-06
  • 1970-01-01
  • 2012-01-16
  • 2020-04-14
相关资源
最近更新 更多