Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Markdown file by heading

Is it possible to sort a markdown file by level 1 heading? Looking for sed or similar command line solution

#B
a content of B

#A
b content of A

to...

#A
b content of A

#B
a content of B
like image 862
HelenFr Avatar asked Oct 31 '22 18:10

HelenFr


1 Answers

A perl one-liner, split for readability

perl -0777 -ne '
    (undef,@paragraphs) = split /^#(?=[^#])/m; 
    print map {"#$_"} sort @paragraphs;
' file.md

You'll want to end the file with a blank line, so there's a blank line before #B. Or you could change
map {"#$_"} to map {"#$_\n"} to forcibly insert one.

like image 75
glenn jackman Avatar answered Nov 15 '22 11:11

glenn jackman