Saved by Regular Expressions

Spotted on reddit:

ls -R | grep “:$” | sed -e ‘s/:$//’ -e ‘s/[^-][^\/]*\//–/g’ -e ‘s/^/ /’ -e ‘s/-/|/’

Or broken down:

ls -R

Do a recursive directory listing, listing all sub-directories, and files. This command on its own is not entirely useful, as it does not give much oversight, unless maybe you are looking for a particular file, in which case find is your friend.

| grep ":$"

Pass the output from ls through to grep, and search for and filter out only lines that end with ‘:’. The $ matches the end of the line.

| sed -e 's/:$//'

Pass the resulting output through to sed (god of regular expression parsers) and strip off the ‘:’ from the end of the line. The ‘e’ option indicates an expression follows. The ‘s’ indicates the expression is a substitution, i.e: match everything between the first / /, in this case ‘:$’, and replace it with everything between the second / /, in this case nothing.

| -e 's/[^-][^\/]*\//--g'

Continue passing the output through sed, and replace every repeating occurrance that isn’t a ‘-‘ or a ‘/’ up until the last ‘/’ with a –.The ‘g’ option at the end indicates we replace every match on the line.

So for example on:


it would match ‘photos/ and fetish/’, thereby replacing the string with

| -e 's/-/|'/

Replace the first ‘-‘ with ‘|’

And now the result? A tree-like directory listing:


Now create an alias:

echo alias tree=”\”ls -R | grep \”:$\” | sed -e ‘s/:$//’ -e ‘s/[^-][^\/]*\//-/g’ -e ‘s/^/ /’ -e ‘s/-/|/’\”” >>~/.bash_profile && . ~/.bash_profile

And you have your very own tree program. Very cool, will work in even the most basic *nix shell. Now, if only I can sort out how to do this in real life.

This entry was posted in IT. Bookmark the permalink.

Leave a Reply

Your email address will not be published.