簡體   English   中英

如何算數 <tr> BASH腳本中HTML表中的行

[英]How to count number of <tr> rows in HTML table from BASH script

我有一個包含表的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行= 2,Type 2行= 2

如果實際數據的格式始終與示例輸入完全相同,則:

$ awk -F"'" '/<tr/{cnt[$2]++} END{for (type in cnt) print type, "rows =", cnt[type]}' file
Type1 rows = 2
Type2 rows = 2

根據@choroba的要求:可能會出錯的地方=整行在一行上,表的一部分被注釋掉,tr具有屬性( <tr style="..."> ),等等。

為此,使用普通的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

這是它的作用:

  1. 對於所有匹配<tr id ='some_id'的文本,它都會增加與some_id相關聯的計數
  2. 最后,對所有找到的ID進行迭代,並打印出它們的關聯計數

正則表達式非常嚴格,因此,如果ID前面有多個空格,或者ID用雙引號引起來,或者在HTML標記可能的許多其他情況下,則該正則表達式將無效。 因此,您可能需要自定義正則表達式。 在某些情況下,修改正則表達式也是不夠的-例如,如果<trid =在不同的行上。 在復雜的情況下,最好使用HTML解析器。

敬請解救!

awk '/<tr / {a[$0]++} END{for(i in a) print i, a[i]}' xml

<tr id='Type2'> 2
<tr id='Type1'> 2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM