Linux Bash:輕鬆刪除 HTML 表資料塊
P粉787806024
P粉787806024 2024-04-02 09:13:43
0
1
319

我有一個使用 bash 腳本處理的 html 文件,並且想要刪除空表。該檔案是從 sql 語句產生的,但在未找到記錄時包含表頭。我想刪除沒有找到記錄的標題。

<table border="1">
  <caption>Table with data</caption>
  <tr>
    <th align="center">type</th>
    <th align="center">column1</th>
    <th align="center">column2</th>
    <th align="center">column3</th>
    <th align="center">column4</th>
   </tr>
   
   Data rows exists here
   
  </table>

<table border="1">
  <caption>Empty Table To Remove</caption>
  <tr>
    <th align="center">type</th>
    <th align="center">column1</th>
    <th align="center">column2</th>
    <th align="center">column3</th>
    <th align="center">column4</th>
    <th align="center">column5</th>
    <th align="center">column6</th>
    <th align="center">column7</th>
  </tr>
</table>

<table border="1">
  <caption>Table with data</caption>
  <tr>
   <th align="center">type</th>
    <th align="center">column1</th>
    <th align="center">column2</th>
    <th align="center">column3</th>
    <th align="center">column4</th>
   </tr>
     Data rows exists here
  </table>

我嘗試使用 grep 和 sed 的組合來刪除空表。當表格包含相同數量的列時,我能夠完成此任務。我現在遇到了一些問題,因為我的表格的列數不同。

當表具有相同數量的列時,我能夠根據標題進行循環,進行計數,然後刪除。由於列數不同,這不起作用。

P粉787806024
P粉787806024

全部回覆(1)
P粉242741921

像這樣,使用

$ xmlstarlet format -H file.html | sponge file.html
$ xmlstarlet ed -d '//table[./caption/text()="Empty Table To Remove"]' file.html 



  
    
Data rows exists here
Table with data
type column1 column2 column3 column4
Data rows exists here
Table with data
type column1 column2 column3 column4

要在 sed -i 等位置進行編輯,請使用

xmlstarlet edit -L ...

沒有解釋,但不要使用sedregex來解析HTML/XML

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!