Shell

從 html 中按模式抓取兩個字元串

  • October 22, 2022
       <DL><p>
           <DT><A HREF="https://www.gnu.org/gnu/" ADD_DATE="1650679138" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQC
AIAAACQkWg2AAACoklEQVQ4jT2PP0hCURTGz729rKwEkR6CkdFreVQSWWGZVItYEA5CZEPQWCC0N4ZCRGNDQw05tCQtIq8peDSUEPZnyyGUCkSLHPIp9917Gh54ho8D349zvo9
wzimlX19f+Xy+2WyOjY0pimKz2SiliNhqtfL5/O/vbygUcrlcQgiCiJqmHRwcAIDX61VVdXV11e/3AwAA3Nzc5HK5t7e3RqOxv78fDofJz8/P7u7u9/f31dWVw+GoVqvFYhEAZ
Fn++PhwuVwTExMAsLOzUy6X0+k0lMvllZWVy8tLRCyVSrFYzLq9tbUVCAS6u7tPTk4Q8fHxcW5u7vX1VTJN0zCMv7+/Wq2WSCTu7+/j8biiKKqqRqPRdDqdSqUmJycZY61WizF
G7Xb74OBgMplcWlqKRCLPz89+v39zc1OWZavr9fX1+vr6xsbG6Oio2+0GzrmmaYFAYHZ2FhE555VKJRgMFgqFUqmkKAoi7u3tLSws6LrOOSdCCEKIruv1en1tbU3TtPHx8b6+P
gDo7++/uLjo7e2dnp4uFAqxWEwIIQkhKKWdnZ0OhyOTyfT09MiyLEnS4eHhwMBAJBJ5eXkpFoszMzNCCACQKKVCiGazmcvlgsHg8PCwzWZ7f3+PRqPVatXj8RiGwTkfGhrinHd
0dFBCCCIuLy+HQiGfz/fw8MAY6+rqqtfr8/Pzn5+f2WzW4/FYyRFRQkTridfrFUKMjIzc3t6Gw+FarXZ6esoYczqddrvdwgghlBBCCAEAVVUrlcri4mImkzk+Pvb5fE6n0zCMe
DxOKbVoAABEREQhBCI2Gg3TNHVdB4BsNnt2dvb09ISIjLE2A+3NUs45Y+z8/FySJAA4OjoSQpimabmIKAGA1aathJDt7W232313dzc1NdXObM0/+0mFhpRFricAAAAASUVORK5
CYII=">gnu/linux</A>
           <DT><A HREF="https://crontab.guru/" ADD_DATE="1651093395" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIA
AACQkWg2AAAB8UlEQVQ4jW2SXUjTURjGn+f4b0XKYrpBYG4j3HY1IpBRDgIJg4IRol304UVgF5kRQRBBEATVuvPOCPGmL+qiO7NMyCi7WMJKsLAbx/BmpEwNUUb8ny7+HzrocD
gczvk973nf5z2Mx9tIkHRWACQAkJQEQAIASRIkWT5tDHcK4MrhcAABAbRIGkNf5nOOxpPCtl2N5dDG0EHJ4MCdo70nWqOhAADALhfm7z6uXrzSNjk08bwCy6eNQeelrvvXUxFg
tVyZnl3bwJ50x4FoJj2aAbA6uUwSFunSuXt9+Z7wVnnx1tX3bxa3s788dmEw01gtLrwEABgSJCK5rnxP+PdM4UhuaqJEb4DkyLMlAF9f/HTIhnA4ZEx4+OmxaK18vndmjaA3na
KbmwINldLtJxXnTYtEpD+Tbaq9uva2tI0Bcp1amfv18LvvGwyA08f3o1p+9AE7DK0bXtcgwQAI7jWobq14TYUA91oSWlp2ux2XJBkAgV3Awdi5+kiSlE6MjA9Mfzx5yDsEYEmY
/bHen2q+WehrzX8ee10NpkOHO2Ldp9o7U43A5viDT9+88BKYSsVJDo2eHczuq0v872bh3dzwjWJRkmDbsm1JYjIZdyxvzybPdEdQq/1Z3liYX5r6su6X4aC2LQlMJGL/+3bwCn
Vpb4N/csD9UHGZQoAAAAAASUVORK5CYII=">Crontab</A>

我想提取描述和href,例如 gnu/linux https://www.gnu.org/gnu/然後傳遞給dmenu

我可以像這樣單獨獲取它們grep -o -P '(?<=">).*(?=</A>)' bookmark.htmlgrep -o -P '(?<=HREF=).*(?= ADD)' bookmark.html但我不知道如何將它們組合起來,甚至不知道如何與 sed 或 awk 組合。

您可以將 HTML 轉換為 XML,然後使用可辨識 XML 的解析器來挑選相關項目。

xmlstarlet format -H index.html 2>/dev/null |
   xmlstarlet select -T -t -m '//a' -v 'concat(., " ", @href)' -n 2>/dev/null

當我在測試時,我將範例提取物包裝在<root>…中</root>,但是您不需要使用 HTML 來執行此操作。結果輸出,每對欄位在一行,空格分隔:

gnu/linux https://www.gnu.org/gnu/
Crontab https://crontab.guru/

您可能會發現最好先提供 URL(沒有空格)然後再提供描述。或使用製表符分隔欄位。

如果您還沒有xmlstarlet它在標準包中,那麼安裝非常容易。

引用自:https://unix.stackexchange.com/questions/721954