This is a website by Willem van Zyl

I'm a project manager, software developer, Apple evangelist and geek from South Africa. I'm passionate about web and mobile application development, usability, productivity, physics, astronomy, science fiction and fantasy.

If you would like to contact me, message me on Twitter or send me an email.

How to display a text-based file and folder tree on the command line

29 Jul 2009

If you need to see a visual layout of files and directories from the current directory in a tree, you can do so by piping the output from a recursive "ls" command into a "grep" search, then piping those results into "sed" replacements to build the tree view.

Open a new Terminal window, switch to the directory you'd like to list, then enter this command:

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

Explanation of the commands

  • ls -R - list all files recursively

  • grep ":$" - find all lines ending in ":" (a colon)

  • sed -e 's/:$//'... - remove all trailing ":" (colons), replace "-" (dashes) with "|" (pipes), and replace "/" (forward slashes) with "–" (double dashes)

Example output

|-Outlook Plugins
|-QuickLook Plugins
|-Quicktime Codecs
|---Perian.component
|-----Contents
|-------MacOS
|-------Resources
|---------English.lproj
|-----------main.nib
|---------French.lproj
|-----------main.nib
|---XviD_Codec-r58 (Intel).component
|-----Contents
|-------MacOS
|-------Resources
|---------English.lproj
|---------XviD_Codec.nib
|---------XviD_Export.nib
Do you like this? Share it:

Copyright © Geekology 2011. All Rights Reserved.

Hosted by Code. Like. Clockwork.