Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!

Display a tree-like structural view of any directory UNIX
First of all this is not my code, I found it on this page via Google, while looking for something that would work like the 'tree' command in Windows.

This guy found a way to do so, using just ls, grep and sed; pretty neat! Here's the command:

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

The author of this useful command even provides a downloadable shell script for the code, and explains how to make a link to ~/bin/tree for those less Unix savvy users. Enjoy!

[robg adds: First, I apologize for the scrolling box, but I didn't want to take any chances on changing the format of the command by inserting a line break, and it was otherwise too wide for display. I'll be the first to admit I don't understand anything in that command past the colon-replacement bit, but it does work quite nicely. Here's a sample of the output, using the shell script from the linked page:
$ tree /Applications | more
/Applications
   |-Address Book.app
   |---Contents
   |-----MacOS
   |-----Resources
   |-------ABLargeTypeWindow.nib
   etc...
You may wish to add | more at the end to page through the output. Or try using > ~/Desktop/mytree.txt at the end to dump the output to a file. I do not, however, recommend doing that with a huge directory such as Applications, unless you have some time to wait. I tried it, and after a few minutes of waiting, wound up with a 1.1mb text file containing 37,000+ rows!]
    •    
  • Currently 3.00 / 5
  You rated: 5 / 5 (5 votes cast)
 
[45,997 views]  

Display a tree-like structural view of any directory | 33 comments | Create New Account
Click here to return to the 'Display a tree-like structural view of any directory' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
Display a tree-like structural view of any directory
Authored by: mankoff on Feb 15, '06 07:16:06AM

Or you can use the 'tree' command. Probably needs to be installed via fink.

---
http://spacebit.dyndns.org



[ Reply to This | # ]
Display a tree-like structural view of any directory
Authored by: os4 on Feb 15, '06 07:16:30AM

What we really need is a Finder add-on (or may another view option, Apple?!) that provides the tree navigation like in Windows explorer. This is one of the very few features of Windows that I believe is superior to the options available right now in the Finder.

I am surprised that someone has not figure out how to hack the Finder app to make the sidebar the tree nav, or at least some type of "drawer" widget attached to Finder windows that provides this navigation.



[ Reply to This | # ]
Path Finder
Authored by: badger brigade on Feb 15, '06 07:54:14AM

Path Finder gives you an outline view, which isn't like the tree view in Windows - it's more like the outline view in Mac OS 9 - but it essentially achieves the same thing.



[ Reply to This | # ]
Outline mode
Authored by: gerwitz on Feb 15, '06 08:20:02AM

How is that different than List View in OS X?



[ Reply to This | # ]
Outline mode
Authored by: solipsism on Feb 15, '06 05:09:55PM

I'm wondering that too.



[ Reply to This | # ]
Outline mode
Authored by: jacobolus on Feb 15, '06 05:15:44PM

it's not



[ Reply to This | # ]
Outline mode
Authored by: badger brigade on Feb 16, '06 03:25:31PM

You're right, it's not. Strange, I guess I'd just never used List View that way before. Maybe having Path Finder fill the whole screen (versus small Finder windows) makes browsing that way more inviting.



[ Reply to This | # ]
Display a tree-like structural view of any directory
Authored by: wgscott on Feb 15, '06 08:21:44AM
I just came up with a truly cheesy way to use the output from tree as an interface to the finder. The tree command gives the output as html. If you open an html file in safari (it would be much better to pipe to it, but I can't figure out how), and click the url to a file on disk, it opens a finder window and highlights the file, rather than opening it in safari. I've always found that behavior irritating, but in this case it can be put to advantage.

It is a truly ugly hack, but maybe someone can make it more elegant.

cd to your top directory of choice, then issue

tree -H rmtag | perl -p -e 's|rmtag/||g' >| junk.html ; \
open junk.html ; \
sleep 6 ; \
/bin/rm -f junk.html
The sleep command gives safari some time to open the file before it gets deleted. It would be much nicer to pipe into safari the output of tree than to do this.

[ Reply to This | # ]
Display a tree-like structural view of any directory
Authored by: jdv on Feb 15, '06 08:42:53AM
You should check out this hint...

[ Reply to This | # ]
Display a tree-like structural view of any directory
Authored by: GlowingApple on Feb 15, '06 07:42:42PM

This creates a temporary file just as the above does (though it's handled by the open command, so there's not worry about a wait time and having to clean up the file afterward.

Problem is that the temp file is created by default with a .txt extension, so when Safari opens it, the code is displayed as a text file, but never rendered as it does with a .html extension.

---
Jayson --When Microsoft asks you, "Where do you want to go today?" tell them "Apple."



[ Reply to This | # ]
Display a tree-like structural view of any directory
Authored by: GlowingApple on Feb 15, '06 08:30:13PM
I couldn't get the perl command to work. The top of the tree shows rmtag as the text still. I'm guessing the / after the rmtag is a typo? In any case, I would prefer to have the top of the tree list the full path of the directory in which tree is working:
tree -H rmtag | perl -p -e "s|rmtag|`pwd`|g" >| junk.html ; \
open junk.html ; sleep 6 ; /bin/rm -f junk.html

---
Jayson --When Microsoft asks you, "Where do you want to go today?" tell them "Apple."

[ Reply to This | # ]

Display a tree-like structural view of any directory
Authored by: ra5ul on Feb 15, '06 10:02:03PM
there's just a backslash missing:
tree -H x | sed 's/x\///' ...

you can get this to work in elinks (any probably other text browsers) with:
tree -aH `pwd` | elinks -force-html

as for safari, it doesn't always open local files in the finder (e.g. *.js, *.pl, *.py open fine on 2.0.3). it seems to be restricted to directories and files it would normally download instead of displaying. there should be a way to specify these files (either in safari's Info.plist or through launchservices), but i don't know how.

[ Reply to This | # ]

!!!
Authored by: ra5ul on Feb 15, '06 10:05:34PM
tree -H x | sed 's/x\///' ... ridiculous.

[ Reply to This | # ]
Display a tree-like structural view of any directory
Authored by: wgscott on Feb 15, '06 10:05:44PM
That actually makes it cleaner. Just do this:

tree -H $PWD > junk.html ; open junk.html ; sleep 6 ; /bin/rm -f junk.html

The other was just designed to trim the ./ from the front of the path. This instead appends the true full path, so it is unambiguous as well as much cleaner. Now if only I could pipe it.

[ Reply to This | # ]
Display a tree-like structural view of any directory
Authored by: wgscott on Feb 15, '06 10:09:08PM
Or even this:

tree -H $PWD > /tmp/$$junk.html ; open /tmp/$$junk.html

[ Reply to This | # ]
Display a tree-like structural view of any directory
Authored by: starwxrwx on Feb 16, '06 12:47:11AM

agreed - great suggestion.

the 'windows explorer' navigation window is the best way to move files around. I love the finder column view generally, but it makes moving files a pain if you have to go up and then down the directory structure, and list view generally takes up too much of the window and again you have to wait to scroll and spring load folders. urg.



[ Reply to This | # ]
Display a tree-like structural view of any directory
Authored by: clops on Feb 15, '06 07:44:27AM

OR just add an alias to your .bash_profile file, something like

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



[ Reply to This | # ]
With Perl
Authored by: galaher on Feb 15, '06 08:32:15AM
This should run as is. If you have the screen real-estate this is a fun way to look at your Mac. I only added a few lines of this code to call the user. You could modify this to take a direcory as an argument from the terminal or from applescript etc. I changed this to my Documents folder and ran this in BBEdit. It's was blazing fast. In about 7 seconds I got 65,000 lines and with my Mighty Mouse I could easily scroll all over this large page.
#!/usr/bin/perl -w
use strict;
use Data::Dumper;
chomp (my $username = `whoami`);
my $base_path = "/Users/$username/Desktop";
print Dumper(&data_for_path($base_path));
sub data_for_path(){
    my $path = shift;
    if(-f $path or -l $path){ # files or symoblic links
        return undef;
    }
    if(-d $path){
        my %directory;
        opendir PATH, $path or die "Cannot opendir $path: $!";
        my @names = readdir PATH;
        closedir PATH;
        for my $name (@names){
        next if $name eq "." or $name eq "..";
        $directory{$name} = &data_for_path("$path/$name");
        }
        return \%directory;
    }
    warn "$path is neither a file nor a directory\n";
    return undef;
}


[ Reply to This | # ]
Display a tree-like structural view of any directory
Authored by: SimonDorfman.com on Feb 15, '06 07:52:30AM
you can also install tree with darwin ports: sudo port install 'tree'

[ Reply to This | # ]
micro-optimization
Authored by: improbability on Feb 15, '06 08:50:21AM

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



[ Reply to This | # ]
Display a tree-like structural view of any directory
Authored by: naam on Feb 15, '06 09:23:09AM

How about just using List View in the finder, then option-clicking the twirly arrow of the directory you need to see the tree structure of? Each time you unfold a folder like this, an extra level of the hierarchy gets displayed.



[ Reply to This | # ]
Display a tree-like structural view of any directory
Authored by: aalegado on Feb 15, '06 01:24:32PM

That works fine if:

1. You only have one window worth of items to list, and,
2. You don't need the actual text of the item list.

The idea behind a utility like 'tree' or the ls/sed pipe in the original hint is that you can get a text-file of the item list.



[ Reply to This | # ]
Display a tree-like structural view of any directory
Authored by: daeley on Feb 15, '06 09:23:30PM

While I would probably go with the CLI option too, if you open a Finder window you can select any files in the hierarchy, copy, and then paste the list into a text editor. However, it does seem to have problems with nested files. YMMV.



[ Reply to This | # ]
Display a tree-like structural view of any directory
Authored by: freew100 on Feb 15, '06 10:18:58AM

You can also get the UNIX command 'pstree' through fink.



[ Reply to This | # ]
Display a tree-like structural view of any directory
Authored by: acet on Feb 15, '06 11:20:35AM
Mind you, this code falls apart pretty quickly in the face of directories or files that have colons (':') in their name. Case in point, run it on ~/Library and watch the fireworks as it trips over Mail and cache subfolders ;)

There's a simple fix, use find instead:


find . -type d | sed -e 1d -e 's/[^-][^\/]*\//--/g' -e 's/^/   /' -e 's/-/|-/'

The additional '-e 1d' sed command gets rid of find always printing '.' and I also tweaked the last sed command for output consistancy.

Oh, not only is this more robust, it's way faster.

Nice tip, I've added it to my toolbelt.

[ Reply to This | # ]

Display a tree-like structural view of any directory
Authored by: kenji on Jul 14, '08 11:02:49AM

Thanks for this version! I removed the "-type d" flag and added "> ~/Desktop/mytree.txt" to get a text file of not only the directory tree, but also the directory's contents. Just what I needed!



[ Reply to This | # ]
Easily Display a tree-like structural view of any directory
Authored by: daflory on Feb 15, '06 11:38:40AM

Why not just drag the folder or volume and drop it into a window in BBEdit or TextWrangler? This gives you a nice indented listing of all files in the folder/volume. It takes a while when I do it for my whole hard drive but it works a treat!

---
Speak softly, study Aikido, & you won't need to carry a big stick!



[ Reply to This | # ]
Easily Display a tree-like structural view of any directory
Authored by: solipsism on Feb 15, '06 05:23:09PM

I really try to stay away from the terminal whenever i can this worked great and was immediate unless I included my Applications folder as it shows you every item in each package.

Excellent tip!



[ Reply to This | # ]
Directories containing spaces break output...
Authored by: cougar718 on Feb 15, '06 12:38:14PM

I just tried both the original hint's method and using find which was recommended by acet and both methods do not work if the directory contains a space. Any idea how to fix it?

---
Rick alias cougar



[ Reply to This | # ]
Display a tree-like structural view of any directory
Authored by: bhughes on Feb 15, '06 04:13:06PM
There is a Finder contextual menu item that can do this, it copies to the clipboard. It's called FileHierToClipCMPlugin (File hierarchy to clipboard) and you can download it at Hsoi's Shop. It doesn't include the "|--" characters but the source is freely available and could be modified to add that.

[ Reply to This | # ]
This output is practically meaningless
Authored by: Lectrick on Feb 15, '06 04:32:50PM

Actually, technically, the output of this is wrong, as the lines are completely meaningless. Compare the output of this to the output of the "tree" command (i installed it with darwinports, it's fast!) for any directory a few layers deep and you'll see that the "left continuation lines" are in multiple layers and actually indicate everything that is still in the same folder (as opposed to this one-liner where they are just decorative). It's actually tough to keep track of that kind of thing using a one-liner.

---
In /dev/null, no one can hear you scream



[ Reply to This | # ]
This output is practically meaningless
Authored by: jacobolus on Feb 15, '06 08:43:56PM

what do you mean the lines are wrong? Every "--" represents a new level. All that it would take to make the output about the same would be to replace strings of more than two --'s with vertical pipe symbols instead of hyphens. This is hardly difficult... just pipe the result fo this back into sed, or modify the original a bit.



[ Reply to This | # ]
Display a tree-like structural view of any directory
Authored by: dogstar on Feb 16, '06 06:29:58AM
I cant get this to work? Any hints anyone?
 ls -R | grep ":" | pi -ctu 'res0fG' | rls -gI 4nt T|t -s  (o )( o) 
Dog

---
Dog

[ Reply to This | # ]