Displaying a text-based file and folder tree on the command line

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

 

Related posts:

  1. Reusing commands with different arguments on a Bash command line
  2. Checking directory sizes on a Bash command line
  3. Editing, Validating and Querying XML with the XMLStarlet command line utility
  4. Mac OS X Quick Tip: Using Spotlight to search from the command line
  5. Ubuntu Linux Quick Tip – Mount a Samba (Windows) file share to a folder
Twitter Digg Delicious Stumbleupon Technorati Facebook Email

2 Responses to “Displaying a text-based file and folder tree on the command line”

  1. Alternativley, use the ‘tree’ command. e.g.

    @:~/example$ tree
    .
    |-- foo
    |   `-- bar
    |       `-- baz
    |-- quuux
    `-- quux
    
    4 directories, 1 file

    You can get it from your favourite repo, e.g. apt-get install tree

  2. Great, thanks Dominic!

Afrigator