Make an index or table of contents in a markdown document
Problem:
I need to make an index or Table of Contents in a markdown document.
For every: ## My title
I have to make a link: My title
Solution:
To buil it automatically, you can use an awk script.
Step by step:
Option 1. Execute the script directly in Terminal.
- Open a
Terminal
and type the awk script:awk '$0 ~ /^## / {gsub(/^## /,"",$0); gsub(/ $/,"",$0); mytitle=$0; $0=tolower($0); gsub(/\(|\)|\[|\]|\/|\:|\./,"",$0); gsub(/ /,"-",$0); print "["mytitle"]""(#"$0")" }' mydatafile.md
- The last awk script get list of links: every link in a new row. If you want a list comma separated you can execute this script:
awk '$0 ~ /^## / {gsub(/^## /,"",$0); gsub(/ $/,"",$0); mytitle=$0; $0=tolower($0); gsub(/\(|\)|\[|\]|\/|\:|\./,"",$0); gsub(/ /,"-",$0); print "["mytitle"]""(#"$0")" }' mydatafile.md | awk '{acumulador=acumulador", "$0}END{print substr(acumulador,3)}'
Option 2. Create awk files and then execute them from Terminal.
- Create the file
make-index-links.md
with these lines:#/bin/bash/awk $0 ~ /^## / {gsub(/^## /,"",$0); gsub(/ $/,"",$0); mytitle=$0; $0=tolower($0); gsub(/\(|\)|\[|\]|\/|\:|\./,"",$0); gsub(/ /,"-",$0); print "["mytitle"]""(#"$0")" }
- Create the file
replace-newline-for-comma-and-space.awk
with these lines:#/bin/awk {acumulador=acumulador", "$0}END{print substr(acumulador,3)}
- Execute from Terminal:
awk -f make-index-links-in-markdown.md mydatafile.md | awk -f replace-newline-for-comma-and-space.awk
Source:
https://www.gnu.org/software/gawk/manual/gawk.html
https://www.gnu.org/software/gawk/manual/html_node/String-Functions.html