Last active
October 21, 2017 10:05
-
-
Save xiangpengzhao/a1d191eb1220dc1a19f92d4a33c09b6b to your computer and use it in GitHub Desktop.
This script updates the TOC of a markdown file. Derived from https://github.com/kubernetes/release/blob/master/lib/common.sh
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# | |
# Copyright 2017 The Kubernetes Authors All rights reserved. | |
# | |
# Licensed under the Apache License, Version 2.0 (the "License"); | |
# you may not use this file except in compliance with the License. | |
# You may obtain a copy of the License at | |
# | |
# http://www.apache.org/licenses/LICENSE-2.0 | |
# | |
# Unless required by applicable law or agreed to in writing, software | |
# distributed under the License is distributed on an "AS IS" BASIS, | |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
# See the License for the specific language governing permissions and | |
# limitations under the License. | |
file=$1 | |
begin_block="<!-- BEGIN MUNGE: GENERATED_TOC -->" | |
end_block="<!-- END MUNGE: GENERATED_TOC -->" | |
tmpfile=/tmp/tmp.md | |
declare -A count | |
while read level heading; do | |
indent="$(echo $level |sed -e "s,^#,,g" -e 's,#, ,g')" | |
# make a valid anchor | |
anchor=${heading,,} | |
anchor=${anchor// /-} | |
anchor=${anchor//[\.\?\*\,\/\[\]()]/} | |
# Keep track of dups and identify | |
if [[ -n ${count[$anchor]} ]]; then | |
((count[$anchor]++)) ||true | |
anchor+="-${count[$anchor]}" | |
else | |
# initialize value | |
count[$anchor]=0 | |
fi | |
echo "${indent}- [$heading](#$anchor)" | |
done < <(egrep "^#+ " $file) > $tmpfile | |
# Insert new TOC | |
sed -ir "/^$begin_block/,/^$end_block/{ | |
/^$begin_block/{ | |
n | |
r $tmpfile | |
} | |
/^$end_block/!d | |
}" $file | |
rm -f $tmpfile |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment