嗨,我正在尝试提取超链接和链接文本
HTML
<tr valign="top">
<td class="beginner">
B03
</td>
<td>
<a href="http://www.drawspace.com/lessons/b03/simple-symmetry">Simple Symmetry</a> </td>
</tr>
<tr valign="top">
<td class="beginner">
B04
</td>
<td>
<a href="http://www.drawspace.com/lessons/b04/faces-and-a-vase">Faces and a Vase</a> </td>
</tr>
<tr valign="top">
<td class="beginner">
B05
</td>
<td>
<a href="http://www.drawspace.com/lessons/b05/blind-contour-drawing">Blind Contour Drawing</a> </td>
</tr>
<tr valign="top">
<td class="beginner">
B06
</td>
<td>
<a href="http://www.drawspace.com/lessons/b06/seeing-values">Seeing Values</a> </td>
</tr>代码
sed -n 's/.*href="\([^"]*\).*/\1/p' file
http://www.drawspace.com/lessons/b03/simple-symmetry
http://www.drawspace.com/lessons/b04/faces-and-a-vase
http://www.drawspace.com/lessons/b05/blind-contour-drawing
http://www.drawspace.com/lessons/b06/seeing-values所需
http://www.drawspace.com/lessons/b03/simple-symmetry Simple Symmetry
http://www.drawspace.com/lessons/b04/faces-and-a-vase Faces and a Vase
http://www.drawspace.com/lessons/b05/blind-contour-drawing Blind Contour Drawing
http://www.drawspace.com/lessons/b06/seeing-values Seeing Values发布于 2022-09-21 16:46:54
第一种解决方案:和您的示例一起,请尝试遵循awk代码。用GNU awk编写和测试。简单的解释是将RS设置为<a href="[^"]*">[^<]* regex,并在主程序中检查RT是否为NULL,并使用split将其值拆分为>或"的删除器,如果满足所有条件,则根据需要输出数组arr的第2和第4值。
awk -v RS='<a href="[^"]*">[^<]*' '
RT && split(RT,arr,"[>\"]"){
print arr[2],arr[4]
}
' Input_file第二个解决方案:使用sed和它的-E选项(为了启用ERE,扩展正则表达式)请尝试下面的代码。使用-n选项来停止sed对行的默认写入。然后在主程序中使用s选项进行替换操作。这里我提到的是[[:space:]]+<a href="([^"]*)">([^<]*).*正则表达式,它将创建两个捕获组,我们将从其中替换完全匹配的文本,然后根据需要使用p选项打印匹配的部分。
sed -E -n 's/[[:space:]]+<a href="([^"]*)">([^<]*).*/\1 \2/p' Input_file第三种解决方案:使用GNU awk的match函数,其中提到regex并创建2个捕获组来获取所需的值。
awk '
match($0,/^[[:space:]]+<a href="([^"]*)">([^<]*)/,arr){
print arr[1],arr[2]
}
' Input_filehttps://stackoverflow.com/questions/73804286
复制相似问题