Skip to content

Instantly share code, notes, and snippets.

@chr5tphr
Last active July 18, 2022 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chr5tphr/e7e9cb4cfbc400eabc01af9b640bee69 to your computer and use it in GitHub Desktop.
Save chr5tphr/e7e9cb4cfbc400eabc01af9b640bee69 to your computer and use it in GitHub Desktop.
Add sectioning and a table of contents to a markdown file
#!/usr/bin/env -S gawk -f
$1~/^##+$/ && $0!~/Table of Contents$/{
intoc = 0
if (l > length($1)) for (k in num) if (k > length($1)) delete num[k]
l = length($1)
num[l] += 1
r = q = substr($0, l + 2)
gsub(" ", "-", q);
toc = toc sprintf("%" ((l - 2) * 4 + 2) "s[%s](#%s)\n", "* ", r, q)
p = ""; for (i in num) p = p num[i] "."
if (length(num) > 1) p = substr(p, 0, length(p) - 1)
gsub("^[0-9.]+ ", "", r)
result = result sprintf("%s %s %s", $1, p, r) ORS
next
}
!intoc{result = result $0 ORS}
$1~/^##+$/ && $0~/Table of Contents$/{
intoc = 1
tocindex = length(result)
result = result ORS
}
END{
printf "%s", substr(result, 0, tocindex) toc substr(result, tocindex + 1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment