Maison  >  Questions et réponses  >  le corps du texte

Linux Bash : supprimez facilement les blocs de données des tableaux HTML

J'ai un fichier html que je traite à l'aide d'un script bash et je souhaite supprimer les tables vides. Le fichier est généré à partir de l'instruction SQL mais inclut des en-têtes lorsqu'aucun enregistrement n'est trouvé. Je souhaite supprimer le titre pour lequel aucune notice n'a été trouvée.

<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>

J'ai essayé d'utiliser une combinaison de grep et sed pour supprimer la table vide. Je suis capable d'accomplir cette tâche lorsque les tableaux contiennent le même nombre de colonnes. J'ai maintenant quelques problèmes car mes tables ont un nombre de colonnes différent.

Lorsque le tableau a le même nombre de colonnes, je peux effectuer une boucle en fonction des en-têtes, compter, puis supprimer. Puisque le nombre de colonnes est différent, cela ne fonctionne pas.

P粉787806024P粉787806024170 Il y a quelques jours323

répondre à tous(1)je répondrai

  • P粉242741921

    P粉2427419212024-04-03 00:19:04

    Comme ceci, en utilisant et  :

    $ 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
    typecolumn1column2column3column4
    Data rows exists here
    Table with data
    typecolumn1column2column3column4

    Pour modifier à sed -i etc., utilisez

    xmlstarlet edit -L ...

    Aucune explication, mais ne pas utilisersedregex来解析HTML/XML

    répondre
    0
  • Annulerrépondre