DEV Community

Saravanan Gnanaguru
Saravanan Gnanaguru

Posted on

Script to Generate Table-of-Content for Markdown file

Table of Content

Introduction

  • I've been writing quite a number of blogs off-late and It is always good practice to have a Table of content to summarise the topics in the blog.
  • Same thing applies to the README.md documentation as well, to have TOC for easy reference and summary
  • But it is a time consuming task to create Table of content for each blog or README documentation
  • So I've created this utility script, which creates the table of content ready to be pasted in the blog markdown file
  • Feel free to use it, in case if you need to create TOC for your README.md file
  • This Utility Script Can be Used to create TOC for Blogging websites which supports MARKDOWN formatting

Script Source

#!/bin/sh
#############################################################
## Script to Create TOC reference in README files
## Step1: Create a file contains with the headings of README file
## Step2: Execute the script with filename as argument
## ./toc-from-headings.sh <file_name_contains_headings>
## The console shows the output with TOC formatting
## Just Copy Paste the Content in your README.md file
#############################################################
toc_filename=$1
echo "## Table of Contents"
cat $toc_filename  | while read line
do
        field2=`echo $line | tr [:upper:] [:lower:] | tr " " "-"`
        echo "- ["$line"]""(#"$field2")"
done

Enter fullscreen mode Exit fullscreen mode

Input File Sample

Introduction
Kubernetes objects
Functionality of Pod
Run the Pod Definition
Verify Pod
Verify the Container Content
Conclusion
Further Reference
Enter fullscreen mode Exit fullscreen mode
  • Save the file as headings.txt

Script Execution and Output

  • Execute the script with file name as input argument
$ ./toc-from-headings.sh headings.txt 
## Table of Contents
- [Introduction](#introduction)
- [Kubernetes objects](#kubernetes-objects)
- [Functionality of Pod](#functionality-of-pod)
- [Run the Pod Definition](#run-the-pod-definition)
- [Verify Pod](#verify-pod)
- [Verify the Container Content](#verify-the-container-content)
- [Conclusion](#conclusion)
- [Further Reference](#further-reference)
Enter fullscreen mode Exit fullscreen mode
  • Tada! Now the TOC is ready in Markdown format and can be pasted in your markdown file.

  • Please note, this script can be used to generate TOC for top level parent headings

  • Visit GitHub repo here for more utility scripts

Latest comments (0)