【发布时间】: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。