ulthar.xyz > Repos

mdtable2csv

A very simple markdown table to CSV converter with no dependencies
About Files Commits git clone https://ulthar.xyz/repos/mdtable2csv/mdtable2csv.git

mdtable2csv/mdtable2csv.awk

Download raw file: mdtable2csv.awk

#!/bin/awk -f
# Convert Github-Flavoured Markdown tables to RFC 4180 CSV

# FIXME: check support with non-gnu awk

BEGIN { FS="\1E" }

function trim(str)   { sub(/^\s+/, "", str); sub(/\s+$/, "", str); return str }
function escape(str) { gsub(/"/, "\"\"", str); return str }
function quote(str)  { return sprintf("\"%s\"", str) }

/^\s*\|(\s*-+\s*\|)+\s*$/ {
	gsub(/\|/, "\1E")
	for (i = 2; i < NF; i++)
		printf(i == NF - 1 ? "" : ",")
	printf("\r\n")
}

# FIXME handle uneven rows https://github.github.com/gfm/#example-204
# FIXME handle colon alignment indicator in delimeter row
/^\s*\|.*\|\s*$/ {
	# Replace non-escaped pipes with the ASCII record separator
	gsub(/(^|[^\\])\|/, "\1E")
	# Un-escape escaped pipes
	gsub(/\\\|/, "|")
	# Strip leading record separators
	gsub(/^\s*\1E/, "")
	for (i = 1; i < NF; i++)
		printf("%s%s", quote(escape(trim($i))), i == NF - 1 ? "" : ",")
	printf("\r\n")
}
Generated 2025-02-02 14:17:32 -0800 by RepoRat