Sorting indented text files

Hello,

I'm trying to find a solution or a proper tool for the following job: I need to sort a text document with indented sections, so all levels of indentation are sorted independently for each section.

Particularly, I need this for Cisco routers' running config files to compare them with configuration templates.

Input example:

! comment
command d
command b
command c
! 
interface b
   podcommand b
   podcommand a
!
interface a
   podcommand b
   podcommand a
! 
command a

Expected output:

command a
command b
command c
command d
interface a
   podcommand a
   podcommand b
interface b
   podcommand a
   podcommand b

I've checked sort man page and looked for similar awk scripts, bot to no avail... Any ideas for a quick solution?

best regards
kobel

This will work on your certainly simplified sample file. Not sure it will on real data...:

awk '/!/{next} !/^ +/ {S=$0; print; next} {$0=S " " $0} 1' file | sort | awk 'NF>2 {$1=$2=""}1'
command a
command b
command c
command d
interface a
  podcommand a
  podcommand b
interface b
  podcommand a
  podcommand b

Hi,

thanks a lot for great suggestion!

Following minor modifications to take into account real Cisco configs (e.g. multi-word section names and different white spaces), the final script looks like this:

awk '/!/{next} !/^[^A-Za-z0-9 ]+/ {S=$0; print; next} {$0=S " " $0} 1' file | sort | awk '
BEGIN { prefix="test" } 
{  
if ( match($0, prefix) && length($0)>0 ) 
{ sub(prefix, "", $0) } 
else if ( length($0)>0 ) 
{ prefix=$0  } 
print $0  
}'

I post it for other people, who might find it useful.

thanks again!
Miron