Issue
I want to create markdown with a directory tree listing automatically, in order to be shown in online repos like GitHub in every directory.
So, given that I'm going to use the href="http://linux.die.net/man/1/tree" rel="nofollow noreferrer">Linux tree
command that can be installed on MacOS X using brew install tree
(see here for details), I came out with this solution:
tree --dirsfirst --noreport -I README.md > README.md;sed -i '' '1s/^/```/' README.md;echo \ >> README.md; sed -i '' -e '$s/$/```/' README.md
where the first sed -i '' '1s/^/```/' README.md
is prepending the ```
chars – see Mastering (Github) Markdown for details about supported markdown.
The echo echo \ >> README.md;
is adding a newline. Note here that I'm not using the sed
equivalent sed -i '' -e '$a\' filename
since this only adds a newline when it does not exists due to the $a
pattern (see here).
While the last sed -i '' -e '$s/$/```/' README.md
is adding a trailing ```
to the file.
The tree
command tree --dirsfirst --noreport -I README.md
is going to exclude some patterns, put directory first, ignore reporting file and dir count.
The result is going to be something like the following:
```.
├── bin
│ ├── Debug
│ │ ├── SampleLibrary.jar
│ │ ├── cooper.jar
│ │ ├── sugar.data.jar
│ │ ├── sugar.jar
│ │ └── swift.jar
│ └── Release
│ ├── SampleLibrary.jar
│ ├── cooper.jar
│ ├── sugar.data.jar
│ ├── sugar.jar
│ └── swift.jar
├── obj
│ ├── Debug
│ │ └── Android
│ │ ├── ClassLibrary2.elements.FilesWrittenAbsolute.txt
│ │ └── samplelibrary.jar
│ └── Release
│ └── Android
│ ├── ClassLibrary2.elements.FilesWrittenAbsolute.txt
│ └── samplelibrary.jar
├── ClassLibrary2.elements
└── ClassLibrary2.elements.user
```
You can see this markdown README.md here.
This solution is not so efficient and it is limited to -I
pattern options of tree
to filter out unwanted dirs (let's say build directories) or file names, etc. Also it does not work properly to update an existing README.md
markdown.
The solution should work on MacOS X (where sed has some differences to that on Linux).
Solution
One way to get source code markup is to indent everything by four spaces:
tree --dirsfirst --noreport -I README.md | sed 's/^/ /' > README.md
To do it your way, adding a new first and last line with ```
on each, we can do
tree --dirsfirst --noreport -I README.md |
sed '1s/^/```'$'\n''/;$s/$/'$'\n''```/' > README.md
where inserting a newline in the replacement string is done with a C-style escape. Alternatively, we can use "$(printf '\n')"
:
tree --dirsfirst --noreport -I README.md |
sed '1s/^/```'"$(printf '\n')"'/;$s/$/'"$(printf '\n')"'```/' > README.md
These should both work with the sed on macOS.
With GNU sed, it would be a little simpler:
tree --dirsfirst --noreport -I README.md |
sed '1s/^/```\n/;$s/$/\n```/' > README.md
Answered By - Benjamin W. Answer Checked By - Katrina (WPSolving Volunteer)