2011-10-10 56 views
0

我很難過。我有一個HTML文件,我試圖將其轉換爲純文本,並使用sed進行清理。據我所知,sed適用於'流',一次只能處理一行,但有多種方法可以匹配多行模式。
這裏是我的源文件的相關部分:Sed程序 - 刪除的字符串重新出現?

<h1 class="fn" id="myname">My Name</h1> 
<span class="street-address">123 street</span> 
<span class="locality">City</span>&nbsp; 
<span class="region">Region</span>&nbsp;&nbsp; 
<span class="postal-code">1A1 A1A</span> 
<span class="email">[email protected]</span> 
<span class="tel">000-000-0000</span> 

我想這個被製作成以下明文格式:

My Name 

123 street 
City Region 1A1 A1A 
[email protected] 
000-000-0000 

的關鍵在於,城市,地區和郵政編碼現在都在一條線上。
我用sed -f commands.sed file.html > output.txt,我相信下面的sed程序(​​),應該把它放在格式:

#using the '@' symbol as delimiter instead of '/' 
#remove tags 
[email protected]<.*>\(.*\)</.*>@\[email protected] 
#remove the nbsp 
[email protected]\(&nbsp;\)*@@g 
#add a newline before the address (actually typing a newline in the file) 
[email protected]\(123 street\)@\ 
\[email protected] 
#and now the command that matches multiline patterns 
#find 'City',read in the next two lines, and separate them with spaces 
/City/ { 
N 
N 
[email protected]\(.*\)\n\(.*\)\n\(.*\)@\1 \2 \[email protected] 
} 

似乎是有道理的。標籤全部被剝離,然後三條線被放入一個。
Buuuuut它不會那樣工作。下面是結果我得到:

My Name 

123 street 
City <span class="region">Region</span>&nbsp;&nbsp; <span class="postal-code">1A1 A1A</span> 
[email protected] 
000-000-0000 

要我(相對缺乏經驗的)眼睛,它看起來像sed是「遺忘」它所做的更改(剝去標籤)。我將如何解決這個問題?解決方案是在三條命令之後寫入文件,並重新運行sed以獲得第四條命令?我濫用sed嗎?我誤解了'流'部分?

我使用bash外殼程序運行Mac OS X 10.4.11,並使用它隨附的sed版本。

+0

你可能使用'awk'有更好的運氣,因爲這其中有你處理,你可以填入實際變量該文件,然後寫在最後。 –

回答

1

我覺得你很困惑。 Sed一行一行地運行,並在移動到下一行之前運行線路上的所有命令。您似乎認爲它將所有行上的標籤剝離,然後返回並運行剝離線上的其餘命令。事實並非如此。

+0

我可能是(因爲我還在學習)。這很可能是我的錯誤,因爲這正是我所假設的。那麼我將不得不重新思考我的劇本。 –

0

請參閱RegEx match open tags except XHTML self-contained tags ...並停止使用sed。

Sed是一個很棒的工具,但不適用於處理HTML。我建議使用Python和BeautifulSoup,它基本上是爲這類任務而構建的。

+0

這非常有趣。不幸的是,我對Python沒有任何經驗。我正在嘗試使用sed,因爲我知道一些它,我真的需要一個快速和骯髒的解決方案。我會研究這個BeautifulSoup,因爲如你所說,它是爲此量身定製的。 –

0

如果每個PHP文件只有一個數據塊,請嘗試以下(使用SED)

kent$ cat t 
<h1 class="fn" id="myname">My Name</h1> 
<span class="street-address">123 street</span> 
<span class="locality">City</span>&nbsp; 
<span class="region">Region</span>&nbsp;&nbsp; 
<span class="postal-code">1A1 A1A</span> 
<span class="email">[email protected]</span> 
<span class="tel">000-000-0000</span> 

kent$ sed 's/<[^>]*>//g; s/&nbsp;//g' t |sed '1G;3{N;N; s/\n/ /g}' 
My Name 

123 street 
City Region 1A1 A1A 
[email protected] 
000-000-0000