tree--ls, grep, and sed

9:17:00 PM 0 Comments

Unix Tree / Linux Tree

Display Structure of Directory Hierarchy

One-Line Shell Script

ls, grep, and sed

Quiz

Quick, what does the following Unix/Linux command do?

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

If you said, "Well, that's obvious; it shows a graphical representation of the current sub-directories.", you'd be correct.


Example

You can use the command to create a program called tree that would work something like the following:

dem@ubuntu:~$ tree .local

/home/dem/.local
|-share
|---applications
|---desktop-directories

dem@ubuntu:~$ cd apps/firefox
dem@ubuntu:~$ tree

/home/dem/apps/firefox
|-chrome
|---icons
|-----default
|-components
|-defaults
|---autoconfig
|---pref
|---profile
|-----chrome
|-extensions
|---{972ce4c6-7e08-474-a285-320198ce6fd}
|---inspector~mozilla.org
|-----chrome
|-----components
|-----defaults
|-------preferences
|---talkback~mozilla.org
|-----components
|-------talkback
|-greprefs
|-icons
|-plugins
|-res
|---dtd
|---entityTables
|---fonts
|---html
|-searchplugins
|-updates
|---0


Code

Here's the command ready-to-go in a shell script:

tree.sh
#!/bin/sh ####################################################### # UNIX TREE # # Version: 2.2 # # By Dem Pilafian # # File: ~/apps/tree/tree.sh # # # # Displays Structure of Directory Hierarchy # # ------------------------------------------------- # # This tiny script uses "ls", "grep", and "sed" # # in a single command to show the nesting of # # sub-directories. # # # # Setup: # # % cd ~/apps/tree # # % chmod u+x tree.sh # # % ln -s ~/apps/tree/tree.sh ~/bin/tree # # # # Usage: # # % tree [directory] # # # # Examples: # # % tree # # % tree /etc/opt # # % tree .. # # # # Public Domain Software -- Free to Use as You Like # # http://www.centerkey.com/tree # ####################################################### echo if [ "$1" != "" ] #if parameter exists, use as base folder then cd "$1" fi pwd ls -R | grep ":$" | \ sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/ /' -e 's/-/|/' # 1st sed: remove colons # 2nd sed: replace higher level folder names with dashes # 3rd sed: indent graph three spaces # 4th sed: replace first dash with a vertical bar if [ `ls -F -1 | grep "/" | wc -l` = 0 ] # check if no folders then echo " -> no sub-directories" fi echo exit

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard.