weaveoftheride
weaveoftheride

Reputation: 4395

How do I split a markdown file into separate files at the heading

I have a book in markdown format. I want to split it into separate files at the chapter headings. How can I do this?

Upvotes: 12

Views: 10546

Answers (3)

evod
evod

Reputation: 167

I needed that exact functionality and was not content with the solutions provided in the other answers mostly because heading tags within code blocks were not respected which lead to problems with my documents.

So I went ahead and wrote a small python tool named mdsplit to do the job. Install it via pip (pip install mdsplit) and then run this to e.g. split at level 2 headings:

mdsplit input.md --max-level 2

Only later I found out there is already a C++ based tool named mdsplit as well that does about the same:

mdsplit -i input.md -l 2

Upvotes: 4

Pier-Eric Chamberland
Pier-Eric Chamberland

Reputation: 81

I stumbled upon a straightforward solution. Credit goes Christian Tietze and mediapathic!

`gcsplit --prefix='novelname' --suffix-format='%03d.md'  novel-file.md /##/ "{*}"`

https://christiantietze.de/posts/2019/12/markdown-split-by-chapter/

Other options:

https://github.com/marceljs/markdown-split

https://github.com/accraze/split-md

Upvotes: 5

Raniere Silva
Raniere Silva

Reputation: 2697

have a book in markdown format. I want to split it into separate files at the chapter headings. How can I do this?

If you are using Pandoc, you can convert your Markdown file to EPUB, unzip the EPUB file and convert the HTML files into Markdown. Not the perfect solution but you can accomplish it with a few lines of bash script like

pandoc -f markdown -t epub -o my-book.epub my-book.md
unzip my-book.epub
for chapter in *.html
do
pandoc -f html -t markdown -o ${chapter/html/md} ${chapter}
done

You need to fix the path to the HTML files.

If you want to program something and you have some experience, shouldn't be hard to write a Python/... script to split the file.

Upvotes: 8

Related Questions