gpt4 book ai didi

xml - 用 bash 解析 HTML 表格列

转载 作者:数据小太阳 更新时间:2023-10-29 02:26:07 26 4
gpt4 key购买 nike

我正在尝试从 HTML 表格中提取 3 列。我需要主机名、产品 + 地区和添加日期。所以它们将是第 1、3、4 列。

<div class="table sectionedit2">
<table class="inline">
<tr class="row0">
<th class="col0 centeralign">hostname</th>
<th class="col1 centeralign">AKA (Client hostname)</th>
<th class="col2 leftalign">Product + Region</th>
<th class="col3 centeralign">date added</th>
<th class="col4 centeralign"> decom. date </th>
<th class="col5 centeralign"> builder </th>
<th class="col6 centeralign"> build cross-checker </th>
<th class="col7 leftalign"> <strong>decommissioner</strong></th>
<th class="col8 centeralign">customer managed filesystems</th>
<th class="col9 centeralign"> only company has root? </th>
</tr>
<tr class="row1">
<th class="col0 centeralign">HostName01</th>
<td class="col1 leftalign">Host01</td>
<td class="col2 leftalign">EU</td>
<td class="col3 centeralign">2007-01-01</td>
<td class="col4 leftalign"></td>
<td class="col5 centeralign">Me</td>
<td class="col6 centeralign">You</td>
<td class="col7 leftalign">Builder01</td>
<td class="col8 leftalign">xChecker01</td>
<td class="col9 centeralign">yes</td>
</tr>
<tr class="row2">
<th class="col0 centeralign">HostName02</th>
<td class="col1 leftalign">Host02</td>
<td class="col2 leftalign">U.S</td>
<td class="col3 centeralign">2008-09-29</td>
<td class="col4 leftalign"></td>
<td class="col5 leftalign">Me01</td>
<td class="col6 leftalign">You01</td>
<td class="col7 leftalign">Builder02</td>
<td class="col8 leftalign">xChecker02</td>
<td class="col9 centeralign">yes</td>

我想得到:

Hostname     Product + Region   Date added

HostName01 EU 2007-01-01

HostName02 U.S 2008-09-29

之前我尝试剥离 HTML 标签并使用 awk,尽管表中的某些列是空的。这意味着我没有得到所有行的第 1、3 和 4 列。

我正在尝试使用:

xmllint --html --shell --format table.log <<< "cat //table/tr/th/td[1]/text()"

这给了我第二列,我尝试了“[0]”,但它不起作用,我不确定如何一次获取多个列。

最佳答案

您可以执行以下操作:

  • 运行xmllint --xpath使用 position()= 的 XPath 表达式仅获取第 1、3 和 4 列://table/tr/*[position()=1 or position()=3 or position()=4]
  • 管道通过perl -pe "s/<th class=\"col0/\n<th class=\"col0/g"等,去除标记并将其分解成单独的行
  • 管道通过 grep -v '^\s*$'去除空行
  • 管道通过 column -t最后漂亮地打印出来

像这样:

xmllint --html \
--xpath "//table/tr/*[position()=1 or position()=3 or position()=4]" \
table.log \
| perl -pe "s/<th class=\"col0/\n<th class=\"col0/g" \
| perl -pe 's/<tr[^>]+>//' \
| perl -pe 's/<\/tr>//' \
| perl -pe 's/<t[dh][^>]*>//' \
| perl -pe 's/<\/t[dh]><t[dh][^>]*>/|/g' \
| perl -pe 's/<\/t[dh]>//' \
| grep -v '^\s*$' \
| column -t -s '|'

上面假设 HTML 文档在文件 table.log 中(这对于 HTML 文件来说似乎是一个奇怪的名称,但它似乎是问题中使用的名称......)。如果文件实际上在其他一些*.html文件,当然只是输入实际的文件名。

这会给你这样的输出:

hostname    Product + Region  date added
HostName01 EU 2007-01-01
HostName02 U.S 2008-09-29

关于xml - 用 bash 解析 HTML 表格列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32480931/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com