Shell Script – Sorting Files into Directories and Subdirectories

shell-script

I routinely write my notes in markdown in a complex directory structure like this.

~/doc/doc.md
~/doc/math/linearAlgebra/linearAlgebra.md
~/doc/math/linearAlgebra/numericalAnalysis.md
~/doc/linux/tmux/tmux.md
~/doc/linux/newsbeuter/newsbeuter.md

This directory structure is ever expanding and each directory has various other files apart from the *.md files. I have a shell script that recursively looks for markdown files in the parent directory doc/ and generates html and pdf files using pandoc. I also create a doc.md file (through the script) which contains a list of all the *.md files. Presently I use,

find ~/doc/**/*.md

to generate this list. I would like to sort them according to the directory structure for easy perusal like this:

math
   linearAlgebra
                          linearAlgebra.md
                          numericalAnalysis.md
linux
   tmux
                          tmux.md
   newsbeuter
                          newsbeuter.md

If fp=/home/user/doc/linux/tmux/tmux.md is an example full path of a file, then ${${fp%/*.md}#/home/user/doc/} gives me linux/tmux. I can further process it to isolate linux and tmux etc. But I don't know the algorithm to create the directory structure. I think that this will require use of arrays to store the complete directory structure for each file and then sorting it.

If a shell script already exists to to this, please let me know. Otherwise, pointers on possible algorithm are welcome.

Best Answer

If all you are looking to do is produce a nice formatted output of all .md files, tree should do exactly what you want:

tree -P '*.md' /home/user/doc

Add -A for pretty lines, it also does interesting things like output to HTML/XML.

Related Question