Monday, May 21, 2012

Sub Directories Tree Script: Sed

When working on the shell sooner or later one realizes that "sed" is a basic tool that although it seems to be a bit confusing at first glance, if you learn how to use it, on the long run will help you a lot.

The best way to learn how to use sed for me is by examples. So here is a script that shows all sub directories in a path with a tree-like look.

It's based on a script by Dem Pilafian I found somewhere on the Internet.

The script shows the sub directories tree on the current path if no argument is provided or the sub directories tree of the provided path.

Usage: ./lstree.sh [<path>]
Script code:
out.sh
     1  #!/bin/bash
     2  
     3  # if path is provided then list directories in path
     4  if [ ! -z "$1" ] && [ ! -d "$1" ]; then
     5    echo "$1: directory not found"
     6    exit 1
     7  elif [ ! -z "$1" ]; then
     8    cd "$1"
     9  fi
    10  
    11  # show actions
    12  pwd
    13  echo '   |'
    14  ls -R | grep ':$' | sed -r 's/:$//' | sed -r 's/[^/]*\//---/g' | sed -r 's/(-*)-/   |\1>/' | 
                                                                                    sed '/\./d'
    15  
    16  # check if no folders
    17  if [ `ls -F -1 | grep "/" | wc -l` = 0 ]
    18    then echo "-> no sub-directories"
    19  fi
    20  
    21  exit 0
Sample output:

Line 14 is the line that does all the "magic":

  • sed #1: removes the trailing colons
  • sed #2: replaces sub directories with "---"
  • sed #3: replaces the first and the last "-" with "|" and ">" respectively
  • sed #4: removes the "." line (current directory)

Sometimes it is hard for me to figure out what is the regular expression defined in a sed command actually matching. 
Lets take the 2nd sed and pipe a fake path to it:


All regular expression matches have been replaced because of the "g" at the end of the sed command. Now, replacing the "g" with numbers starting from 1 to N, one can see what are the single substitutions that have been made:



That's a simple way to check what the regular expression defined in the sed command is actually matching.

As I said at the beginning of this post, spend some time learning sed!


1 comment:

  1. Not an IT guy but always keen to learn new things, Going to keep this code and show it to my friend who is helping me these days to learn IT stuff. Thanks

    ReplyDelete