2017-02-28 69 views
0

我该如何才能在特定模式中替换字符,最好在sed但awk或其他方式,如果有更简单的选项?我想用连字符( - )替换我的html h3 id中的空格,但我不想让它连字符连接整行。sed替换一行内的模式

例如,在我的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> 

我想什么是3H公司这样的:

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

我已经试过

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

但这种贪婪地增加了连字符。到不应该有连字符的行(第2个)和部分(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。谢谢!

+0

你只需要这一点,4号线? –

+0

不,整个文件。 SLePort的答案就是这样。谢谢k-five。 – kokoro

回答

0

此sed一次替换idh3标记中的一个空格。当替换成功,t命令循环到:a标签来搜索剩余空间来代替:

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

谢谢,这很好!虽然我不认为自己在干什么。 – kokoro

+0

不客气......我更新了命令以限制替换为“id”值。 – SLePort

+0

请阅读[当某人回答我的问题时该怎么办?](http://stackoverflow.com/help/someone-answers)。 – SLePort