Re: display in a tree structure
On 3/26/2008 6:06 AM, Vakayil Thobias wrote:
> I have to display the data from a file in tree structure(ksh).
> The file format is as follows(first field parent, second field child) :
>
> PM01 PM02
> PM01 PM1A
> PM02 PM03
> PM03 PM04
> PM04 PM05
> PM04 PM06
> PM1A PM1B
> PM1A PM1C
>
> The output should be like this :
> PM01 -- PM02 -- PM03 -- PM04 -- PM05
> PM06
> PM01 PM1A -- PM1B
> PM1C
>
> Anybody have idea ?
Here's a start:
$ cat file
PM01 PM02
PM01 PM1A
PM02 PM03
PM03 PM04
PM04 PM05
PM04 PM06
PM1A PM1B
PM1A PM1C
$ cat dt.awk
function descend(indent,branch, child,childA) {
printf "%"indent++"s%s\n","",branch
split(children[branch],childA)
for (child in childA)
descend(indent,childA[child])
}
{
branches[$1]
branches[$2]
children[$1] = children[$1] FS $2
parent[$2] = $1
}
END {
for (branch in branches)
if (!(branch in parent)) {
descend(0,branch)
delete branches[branch]
}
print "-----"
for (branch in branches)
descend(0,branch)
}
$ awk -f dt.awk file
PM01
PM02
PM03
PM04
PM05
PM06
PM1A
PM1B
PM1C
-----
PM05
PM1A
PM1B
PM1C
PM1B
PM06
PM1C
PM02
PM03
PM04
PM05
PM06
PM03
PM04
PM05
PM06
PM04
PM05
PM06
Regards,
Ed.
|