【问题标题】:Sed substitute pattern within a line一行内的 sed 替代模式
【发布时间】:2017-02-28 15:10:56
【问题描述】:

如果有更简单的选项,我如何仅在特定模式中替换字符,最好是在 sed 但 awk 或其他模式中?我想用连字符 (-) 替换我的 html h3 id 中的空格,但我不希望它连字符整行。

例如,在我的 foo.html 中:

<p>This is a paragraph which likes its spaces.</p>

<h3 id="No spaces in this id please">Keep spaces in this title</h3>

<p>Here's another paragraph with spaces.</p>

<h3 id="Another id that should be spaceless">Spaces please!</h3>

<p>Yes I would like extra noodles in my soup.</p>

我想要的是这样的h3:

<h3 id="Another-id-that-should-be-spaceless">Spaces please!</h3>

我试过了

sed -e "/^<h3 id=\"/,/\">/s/ /-/g;" <foo.html >bar.html

但这会贪婪地将连字符添加到不应该有连字符的行(第 2 p)和部分(h3 内容)! Bar.html:

<p>This is a paragraph which likes its spaces.</p>

<h3-id="No-spaces-in-this-id-please">Keep-spaces-in-this-title</h3>

<p>Here's-another-paragraph-with-spaces.</p>

<h3-id="Another-id-that-should-be-spaceless">Spaces-please!</h3>

<p>Yes I would like extra noodles in my soup.</p>

注意我使用的是 GNU sed。谢谢!

【问题讨论】:

  • 第 4 行只需要这个吗?
  • 不,对于整个文件。 SLePort 的回答就是这样做的。谢谢k-5。

标签: regex awk sed


【解决方案1】:

此 sed 在 h3 标签的 id 值中一次替换一个空格。当替换成功时,t 命令循环到:a 标签以搜索剩余的空格进行替换:

sed -e ':a;s/\(<h3[^>]*id="[^"> ]*\) \(.*\)/\1-\2/;ta;' < foo.html > bar.html

【讨论】:

猜你喜欢
  • 2013-11-11
  • 1970-01-01
  • 1970-01-01
  • 2013-08-22
  • 1970-01-01
  • 2016-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多