2017-02-28 52 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