我有一個 xml 檔案,其中列出了幾個游戲及其元資料,如下所示:
<?xml version="1.0"?>
<gameList>
<game>
<path>./Besiege.desktop</path>
<name>Besiege</name>
<desc>Long description of game</desc>
<releasedate>20150128T000000</releasedate>
<developer>Spiderling Studios</developer>
<publisher>Spiderling Studios</publisher>
<genre>Strategy</genre>
<players>1</players>
</game>
<A bunch of other entries>
<game>
<path>./67000.The Polynomial.txt</path>
<name>The Polynomial - Space of the music</name>
<desc>Long description of game</desc>
<releasedate>20101015T000000</releasedate>
<developer>Dmytry Lavrov</developer>
<publisher>Dmitriy Uvarov</publisher>
<genre>Shooter, Music</genre>
<players>1</players>
<favorite>true</favorite>
</game>
<Another bunch of entries>
</gameList>
我想洗掉包含子字串“.desktop”的每個條目并保留所有其余條目。但是僅僅洗掉包含這個字串的行是不夠的,我想洗掉從 <game> 到 </game> 的整個塊。
我知道在 Linux 中,使用 bash,有幾種方法可以洗掉給定字串之前或之后的固定行數。但是通過比較上面的兩個條目,您可以看到它們并不總是具有相同數量的欄位。“<desc>”標簽內的描述也從一到四個段落不等,由空行分隔。我還沒有找到任何處理目標子字串周圍可變行數的解決方案。
我認為有一種簡單的方法可以將文本從開始的 <game> 標記到結束的 </game> 標記分成塊,這樣我就可以像通常對行一樣對它們進行操作,其中案例一個簡單的 while 回圈,測驗子字串的存在并洗掉塊,如果為真,或類似的東西,將解決我的問題。嗯,我一直在努力反對 grep、sed 和 awk,我試圖為 IFS 設定一個方便的值,這樣它只會在“</game>”處結束行,我越來越沮喪,因為我我幾乎到了手動執行此操作會更快的地步。但那時我會保持無知。
我才剛剛開始學習 Bash,所以有很多我不知道的東西,而且我覺得這是知識淵博的人可以用單行代碼做的事情,但我完全被難住了。所以謝謝你的時間,請給我指明正確的方向。
uj5u.com熱心網友回復:
不要使用線條工具編輯 XML 檔案。不要使用 Bash 編輯 XML 檔案。使用 XML 工具編輯 XML 檔案。用 Python 或 Perl 或其他具有 XML 庫的功能強大的編程語言撰寫程式來編輯 XML。
下面的 xmlstarlet 非常簡單:
$ xmlstarlet ed -d '/gameList/game[ contains(path, ".desktop") ]' input.xml
<?xml version="1.0"?>
<gameList>
<game>
<path>./67000.The Polynomial.txt</path>
<name>The Polynomial - Space of the music</name>
<desc>Long description of game</desc>
<releasedate>20101015T000000</releasedate>
<developer>Dmytry Lavrov</developer>
<publisher>Dmitriy Uvarov</publisher>
<genre>Shooter, Music</genre>
<players>1</players>
<favorite>true</favorite>
</game>
</gameList>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/536803.html
