Skip to content

Instantly share code, notes, and snippets.

@daniel-vera-g
Created October 25, 2020 14:36
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 daniel-vera-g/69e3fb8a6d7d9d7c86b2539fcd066521 to your computer and use it in GitHub Desktop.
Save daniel-vera-g/69e3fb8a6d7d9d7c86b2539fcd066521 to your computer and use it in GitHub Desktop.
Update Markdown table of contents using markdown-toc npm package and linux utilities
#!/bin/sh
# Remove current toc:
# 1. Use sed to remove everything till the first heading
# 2. Write it to tmp file
# 3. When no errors merge it with index file
sed -n '/^#/,$p' index.md > tmp \
&& yes | mv tmp index.md
# Create table of contents:
# 1. Create toc with markdown-toc and save in tmp file
# 2. Add linebreak at the end of the toc file
# 3. Concatenate tmp back with the index file
# 4. When no errors occurred in concatenation process, merge tmp with index
# markdown-toc index.md > tmp && \
# echo \ >> tmp && \
# cat tmp index.md > tmp && \
# yes | mv tmp index.md
markdown-toc index.md > tmp && echo \ >> tmp && cat tmp index.md > tmp2 && yes | mv tmp2 index.md
# cleanup
rm tmp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment