html table csv,How can I convert an HTML table to CSV?

Sorry for resurrecting an ancient thread, but I recently wanted to do this, but I wanted a 100% portable bash script to do it. So here's my solution using only grep and sed.

The below was bashed out very quickly, and so could be made much more elegant, but I'm just getting started really with sed/awk etc...

curl "http://www.webpagewithtableinit.com/" 2>/dev/null | grep -i -e '\?TABLE\|\?TD\|\?TR\|\?TH' | sed 's/^[\ \t]*//g' | tr -d '\n' | sed 's/]*>/\n/Ig' | sed 's/]*>//Ig' | sed 's/^]*>\|]*>$//Ig' | sed 's/]*>]*>/,/Ig'

As you can see I've got the page source using curl, but you could just as easily feed in the table source from elsewhere.

Here's the explanation:

Get the Contents of the URL using cURL, dump stderr to null (no progress meter)

curl "http://www.webpagewithtableinit.com/" 2>/dev/null

.

I only want Table elements (return only lines with TABLE,TR,TH,TD tags)

| grep -i -e '\?TABLE\|\?TD\|\?TR\|\?TH'

.

Remove any Whitespace at the beginning of the line.

| sed 's/^[\ \t]*//g'

.

Remove newlines

| tr -d '\n\r'

.

Replace with newline

| sed 's/]*>/\n/Ig'

.

Remove TABLE and TR tags

| sed 's/]*>//Ig'

.

Remove ^

, ^, $, $

| sed 's/^]*>\|]*>$//Ig'

.

Replace

with comma

| sed 's/]*>]*>/,/Ig'

.

Note that if any of the table cells contain commas, you may need to escape them first, or use a different delimiter.

Hope this helps someone!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值