One Line Linux Command to Print Out Directory Tree Listing

From systembash.com

My professor sent us this little one liner which prints out the current directory tree:

ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' \-e 's/^/ /' -e 's/-/|/'

What’s going on here?

* ls -R — list files and directories recursively
* grep “:$” — find lines with : at the end (so only the directories)
* sed -e — evaluate expressions on the lines
* s/:$// — remove ‘:’ at the end of the line
* s/[^-][^\/]*\//–/g — replaces text between / / lines (parent directories) with — , globally on each line
* s/^/ / — add space at the beginning of the lines
* s/-/|/ — replace first – of the line with |

I reduced this using the following command. The most notable difference is that I use find instead of ls, which results in also viewing .hidden directories. I’m not sure which command is faster.

find ./ -type d | sed -e 's/[^-][^\/]*\//--/g;s/--/ |-/'

Both commands result in a formatted directory listing, demonstrated below:

|-sitetransfer
|---redacteddomain.com
|-----cache
|-----templates
|-------skidoo_too
|---------images
|-----------_vti_cnf
|---------css
|-----------_vti_cnf
|---------js
|-----------scriptaculous
|-------------src
|-------------lib
|---------admin_templates

Of course you can also use

pstree

g33kadmin

I am a g33k, Linux blogger, developer, student and Tech Writer for Liquidweb.com/kb. My passion for all things tech drives my hunt for all the coolz. I often need a vacation after I get back from vacation....

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.