RegEx用于从字符串中删除html垃圾的bash脚本

时间:2013-08-24 09:40:16

标签: html regex bash

由于某些原因,我从脚本中获取输出,该脚本使用一些我不需要的额外HTML代码来抓取html页面。

这就是我的意思:

... MY DATA IN A SINGLE ROW FOLLOWED BY ...> <script>function fbs_click() {u=location.href;t=document.title;window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');return false;}</script><style> html .fb_share_button { display: -moz-inline-block; display:inline; padding:1px 11px 0 5px; height:15px; border:1px solid #d8dfea; background:url(http://static.ak.facebook.com/images/share/facebook_share_icon.gif?6:26981) no-repeat top right; } html .fb_share_button:hover { color:#fff; border-color:#295582; background:#3b5998 url(http://static.ak.facebook.com/images/share/facebook_share_icon.gif?6:26981) no-repeat top right; text-decoration:none; } </style> <a rel="nofollow" href="http://www.facebook.com/share.php?u=/dizionario/recensi ne.asp?id=11334" class="fb_share_button" onclick="return fbs_click()" target="_blank" style="text-decoration:none;"></a>

也许这个额外的代码可以用REGEXP删除,删除标签旁边的字符串的所有内容和包含的标签..

1 个答案:

答案 0 :(得分:3)

使用正则表达式删除html标签(以及脚本和样式)并不总是很容易,但是由于您正在寻找一种bash方式,您可以使用一个简单的技巧:使用文本浏览器(lynx,links,w3m),示例:

lynx -dump input.html > output.txt

或者您可以将内联工具xidel与XPath查询一起使用:

xidel ./input.html --extract "//text()[not(parent::style|parent::script)]"

您也可以尝试使用正则表达式,但它不那么安全:

sed 's/<script.*<\/script>\|<style.*<\/style>\|<[^>]*>//g' input.html

(请注意,此正则表达式失败,例如:<script>sfsdfsfsdf</script> CONTENT <script>sdfsdfsdf</script>

或者您可以在html上下文中使用这个更安全的正则表达式:

sed -r 's/<script([^<]|<[^\/]|<\/[^s]|<\/s[^c])*<\/script>|<style([^<]|<[^\/]|<\/[^s]|<\/s[^t])*<\/style>|<[^>]*>//g' input.html

您可以通过在最后一个案例之前添加捕获组(即|<[^>]*>)轻松保留“a”和“strong”等标记:

|(<a ([^<]|<[^\/]|<\/[^a]|<\/a[^>])*<\/a>|<strong([^<]|<[^\/]|<\/[^s]|<\/s[^t]|<\/st[^r])*<\/strong>)

然后将替换模式更改为$3(它是模式的第三组)