printing directories in tree structure using awk

Awk and gawk scripting forum.

printing directories in tree structure using awk

Postby james on February 7th, 2008, 6:50 pm

I recently saw some code (url: http://www.centerkey.com/tree/) to print directory structure as a tree:
Code: Select all
ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/   /' -e 's/-/|/'

However, I think the following in awk is easier to read (mainly because it is not sed), and also does not stumble on files that end in ':',
the output is also sorted in alphabetical order
Code: Select all
du | awk '{print $2}' | sort |  awk 'BEGIN{FS="/"}NF>1{printf"|"; for(i=1;i<2*(NF-1);i++){printf "-"};print $NF}'

example:
Code: Select all
|-JCopy
|-MFCC
|---outputs
|-gmm_train
|---outputs
|---mfc1

Does anyone else have any nifty implementations?
james
Member
 
Posts: 18
Joined: January 18th, 2008, 2:27 pm

Re: printing directories in tree structure using awk

Postby james on February 7th, 2008, 7:26 pm

if you want to include files and have them treated differently to directories, the following works:
Code: Select all
for i in `du -a | awk '{print $2}' | sort`; do echo $i | awk 'BEGIN{FS="/"}NF==1{next}{for(j=1;j<2*(NF-1);j++)printf " "}a==1{print "+-"$NF}a==0{print "d-"$NF}' a=`[ -d $i ]; echo $?`; done

this prints a "+" in front of files, and keeps the letter "d" in front of dirs
example output:
Code: Select all
d-acml
   +-acml-3-6-0-gnu-64bit.tgz
   +-README.64-bit
+-a.out
d-gmm_test
   +-filelist.txt
   +-gte_htk.c
   +-Makefile
   d-out
     +-person1.gmm
     +-person2.gmm
   +-person1.gmm
d-gmm_train
   +-1_sa1.mfc
   +-callgrind.out.17834
   +-gmm_train
james
Member
 
Posts: 18
Joined: January 18th, 2008, 2:27 pm


Return to Awk

Who is online

Users browsing this forum: No registered users and 0 guests

cron

dsplabs homelinux bloglinux forums new!travel photography
©2012 dsplabs.com.au