Automatic TOC in github-flavoured-markdown

后端 未结 17 1745
伪装坚强ぢ
伪装坚强ぢ 2020-12-12 09:24

Is it possible to generate an automatic Table of Contents using Github Flavoured Markdown?

17条回答
  •  不知归路
    2020-12-12 10:02

    Here's a shell script I threw together today for this. Might need to tweak it for your needs, but it should be a good starting point.

    cat README.md \
        | sed -e '/```/ r pf' -e '/```/,/```/d' \
        | grep "^#" \
        | tail -n +2 \
        | tr -d '`' \
        | sed 's/# \([a-zA-Z0-9`. -]\+\)/- [\1](#\L\1)/' \
        | awk -F'(' '{for(i=2;i<=NF;i++)if(i==2)gsub(" ","-",$i);}1' OFS='(' \
        | sed 's/^####/      /' \
        | sed 's/^###/    /' \
        | sed 's/^##/  /' \
        | sed 's/^#//'
    

    If anyone knows a better way to do those final # replacements, please add a comment. I tried various things and wasn't happy with any, so I just brute forced it.

提交回复
热议问题