使用Sed处理HTML片段:处理含数十条记录的长HTML表格
Got it, let's break down how to use Sed to work with those HTML table rows you've got. First, let's start with your sample row for reference:
<tr onclick="window.location='/team/90687/'" style="cursor: pointer;" class=""> <td class="number">163124</td> <td class="img">3</td> <td class="user"> <span class="name">Mosse John</span> </td> <td class="number">3332</td> <td class="number">497</td> <td class="number">20</td> </tr>
Below are common tasks you might want to perform, with corresponding Sed commands:
1. 提取特定字段(比如编号和用户名)
If you need to pull out structured data like the user ID (163124) and name (Mosse John) into a clean, CSV-like format, use this command:
sed -n 's/.*<td class="number">\([0-9]*\)<\/td>.*<span class="name">\([^<]*\)<\/span>.*/\1,\2/p' your_table.html
-nsuppresses default output, so we only print lines where we find a match- The regex uses
\([0-9]*\)and\([^<]*\)to capture the number and name groups \1,\2outputs the captured groups separated by a comma for easy parsing
2. 修改链接地址
If you want to update the onclick URL (e.g., change /team/ to /player/), use this escaped command to handle single quotes correctly:
sed 's/onclick="window.location='\''\/team\/\([0-9]*\)\/'\''"/onclick="window.location='\''\/player\/\1\/'\''"/' your_table.html
- We escape single quotes with
'\''to preserve them in the Sed command \([0-9]*\)captures the team ID, so we can reuse it in the new URL with\1instead of hardcoding values
3. 清理不必要的属性
To remove style and class attributes from the <tr> tags (simplify the markup):
sed -e 's/ style="[^"]*"//g' -e 's/ class="[^"]*"//g' your_table.html
-elets us run multiple edit commands in one go[^"]*matches any character except a quote, so it targets the entire attribute value without breaking surrounding code
Quick Note
Sed works great for simple, structured HTML like your table rows. For more complex HTML with nested tags or unpredictable formatting, tools like xmllint or awk (with HTML-aware parsing) might be more reliable—but for your use case, these Sed commands should do the trick.
内容的提问来源于stack exchange,提问作者linux_beginner

