converting config file to csv format

Hello,

For 2 days now i've been searching for a solution to this. I am now beginning to doubt this is even possible. It's even harder when you don't know how to search for it. (which keywords generate enough relevancy etc..)

I need to parse a config file to generate a CSV file in return.
It would need to take these parameters out of the file:

define host{

    host_name               hostA
    parents                 hostNull
    \}

--
define host{

    host_name               hostB
    parents                 hostA
    \}

--
define host{

    host_name               hostC
    parents                 hostB
    \}

--

and create this:

host,parent
hostA,hostNull
hostB,hostA
hostC,hostB

Does anyone know a solution to this or can someone point me out to some doc that explains how ?

From what info you provided, this is one approach.

> cat bld_csv 
#! /bin/bash

echo "host,parent" >host.csv
while read zf
  do
  hck=$(echo "$zf" | cut -d" " -f1)
  if [ "$hck" = "host_name" ]
    then
    hnm=$(echo "$zf" | cut -d" " -f2)           
  fi
  if [ "$hck" = "parents" ]
    then
    pnm=$(echo "$zf" | cut -d" " -f2)
    echo $hnm","$pnm >>host.csv
  fi

done < sample

Another approach:

awk ' 
BEGIN{print "host,parent"}
/host_name/{p=$2;getline;print p","$2}
' sample

Regards

$ cat temp.txt | perl -ne 'chomp; print "host,parent\n" if $. == 1; print $_ if $_ =~ s/^host_name\s+(.*)$/$1/;  print ",$_\n" if $_ =~ s/^parents\s+(.*)$/$1/;'

host,parent
hostA,hostNull
hostB,hostA
hostC,hostB
  1. Print the headers on first line of input.

  2. Print the host name if found (with no newline)

  3. Print the comma, parent name, and newline when parent is found.

ShawnMilo

nawk 'BEGIN{RS="--";n=1;host[n]=sprintf("host,parent")}
{
n=n+1
host[n]=sprintf("%s,%s",$4,$6)
}
END{
for(i=1;i<=n;i++)
if(host!=",")
print host
}
' filename

awk '
BEGIN { print "host,parent" }
/host_name/ {printf "%s,",$NF; getline; print $NF}
' $INFILE

-Ramesh

Thank you very much for all your replies, i will give them a try today and let you know how it turned out.

Ok. I went with Franklin's awk solution and it works beautifully.
I also expanded it to include a third column named alias and also modified the code in such a way that it understands the space separated fields of the alias line.

define host{
host_name HostA
alias Also Known As Host A
parents HostNull
}
--
define host{
host_name HostB
alias Also Known As Host B
parents HostA
}

awk 'BEGIN {print "host,alias,parent"}
/host_name/{p=$2;printf p",";getline;
pi=NF;for (i=2;i<pi+1;i++) printf $i" ";getline;
p3=$2;print "\b,"p3}
' source.txt

host,alias,parent
HostA,Also Known As Host A,HostNull
HostB,Also Known As Host B,HostA

Thanks again. This is just what i needed.