I found this bash command that creates a directory tree in your console window. I find it quite useful, but I don't really understand how all of the special characters work. Could someone help break it down for me?

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

The first two are pretty simple to understand, this is creating an alias in bash that recursively lists the files and folders beneath the current directory.

1. alias tree="" 
2. ls -R

But after those I'm pretty much lost. I get that it's piping the rest of the commands through grep and sed, but I don't understand the rest of it or even what these modifiers are called.

closed as too broad by Braiam, mdpc, Michael Homer, don_crissti, Celada Mar 21 '15 at 5:44

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

alias tree="ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/   /' -e 's/-/|/'"
  • ls -R: list subdirectories recursively
  • grep ":$": grep only for lines with : at the end of the line
  • sed -e 's/:$//': remove : at the end of the line
  • -e 's/[^-][^\/]*\//--/g': replace all path components except of last dir with --. To be precise replace any char except of - followed by any char except of / repeated zero or more times and then followed by /.
  • -e 's/^/ /': add 3 spaces at the beginning of the line
  • -e 's/-/|/': replace first - with |

There are many "problems" with this snippet starting with parsing of ls command, but leaving this aside, you can rewrite sed part in more compact way:

ls -R | grep ":$" | sed -e 's/:$//;s/[^-][^\/]*\//--/g;s/^/   /;s/-/|/'
  • 1
    Don't parse the output of ls.. – Avinash Raj Oct 26 '14 at 11:31

Not the answer you're looking for? Browse other questions tagged or ask your own question.