我的html文件包含一个包含3个不同ID的行的表格,如和 我的要求是我需要使用BASH脚本获取每种行的计数。
很抱歉没有提供样本i / p:
<table border="1">
<tr id='Type1'>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
</tr>
<tr id='Type2'>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
</tr>
<tr id='Type1'>
<td>Row 3, Column 1</td>
<td>Row 3, Column 2</td>
</tr>
<tr id='Type2'>
<td>Row 4, Column 1</td>
<td>Row 4, Column 2</td>
</tr>
</table>
来自shell的预期o / p是:Type1 rows = 2,Type 2 rows = 2
答案 0 :(得分:4)
如果您的实际数据的格式与样本输入完全相同,那么:
$ awk -F"'" '/<tr/{cnt[$2]++} END{for (type in cnt) print type, "rows =", cnt[type]}' file
Type1 rows = 2
Type2 rows = 2
Per @ choroba的请求:可能出错的一些事情=一行上的整个表格,表格的一部分被注释掉,tr有属性(<tr style="...">
)等等。
答案 1 :(得分:2)
使用普通的bash脚本会比必要的更复杂。我会建议Perl。如果我们假设您的所有输入文件与示例或多或少相似,则以下内容应该起作用:
# If all the HTML documents in your set are in the same format as your sample
perl -lne '$rows{$_}++ for '"/<tr id='([^']*)'/g"'; END { print "$_ rows=$rows{$_}" for keys %rows; }' filename
以下是它的作用:
正则表达式是相当严格的,因此如果ID之前有多个空格,或者如果ID是双引号,或者在HTML标记中可能出现的许多其他情况下,它将无效。所以你可能需要自定义正则表达式。在某些情况下,修改正则表达式也是不够的 - 例如,如果&lt; tr 和 id = 在不同的行上。在复杂的场景中,使用HTML解析器是最好的。
答案 2 :(得分:1)
要求救援!
awk '/<tr / {a[$0]++} END{for(i in a) print i, a[i]}' xml
给出
<tr id='Type2'> 2
<tr id='Type1'> 2