tree-like ls

tree” is a very nice command that’s not always available on any systems. As the name implies it lists the contents of directories in a tree-like format.

An example is:

$ tree
.
|-- Boards
|-- Members
|-- Messages
|-- Settings.pl
|-- Sources
|-- Variables
|-- YaBB.cgi
|-- english.lng
|-- template.html
`-- template2.html

Well, a similar result can be achieved in Bash with a nifty little one-liner:

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

NOTE: long line, I had to break/fold it, sorry about that. Copy&paste is fine as long as the backslash (“\”) at the end of the first line is preserved.

A short explanation of the cryptic syntax above is as follows:

  • initially a recursive listing of the current directory is done: ls -R
  • pipe
  • any output other that the directory names, identified by “:” at the very end of each line (hence “:$“), is filtered out: grep ":$"
  • pipe
  • finally there’s a little of “sedmagic finding and replacing any hierarchy level (“/“) with one or more dashes (“-“):
    sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/ /' -e 's/-/|/'

Leave a comment