Script generate-insert-table-of-content-markdown.sh
The snippet can be accessed without any authentication.
Authored by
Arturos Sanchez Pineda
This script produces and inserts a Table of Content in a markdown file, following the corresponding rules for H1, H2,... markdown titles.
Important notes
- The file uses as parameter
$1
the name of the file. - If no file is given, by default look for a
README.md
- Before to execute the script, please insert this HTML line at the very beginning of the markdown file.
- Or technically wherever you want the table of content to ends.
<!-- end-of-table-of-content -->
Cheers,
Arturo
generate-insert-table-of-content-markdown.sh 1019 B
#!/usr/bin/env bash
## Script to generate and add to the Top of a markdown file a table of content
## It uses one parameter that is the name of the markdown file. If none is given, it will look for "README.md"
## arturos@cern.ch
## 25/Jun/2019
## Get the name of the file to create the table of content (default is README.md)
file="${1:-README.md}"
## *unique* pattern to look into the file to generate the table of content
## Insert the next HTML line at the beginning of the file (i.e. where the Table of Content will end)
## <!-- end-of-table-of-content -->
## Remove previous Table of Content
sed -n '/end-of-table-of-content/,$p' $file > _tmp && mv _tmp $file
## Generate new Table of Content
grep -E "^#{1,5} " $file | sed -E 's/(#+) (.+)/\1:\2:\2/g' | awk -F ":" '{ gsub(/#/," ",$1); gsub(/[ ]/,"-",$3); print $1 "- [" $2 "](#" tolower($3) ")" }' > _table.txt
## Insert the new table in the file
cat _table.txt | cat - $file > _tmp && mv _tmp $file
## clean temporary file(s)
rm -rf _table.txt
## end script
Please register or sign in to comment