Converting form field to table format

May data

   Name = Andi
Address = none
   Phone = 82728

   Name = Peter
Address = none
   Phone = 98799

The expected output

Name,Address,Phone
Andi,none,82728
Peter,none,98799

what i have done

$ awk -F"=" '{print $2}' data.txt |paste -sd ,
 Andi, none, 82728,, Peter, none, 98799

Thx in Adv.

Try:

awk -F'=[ \t]*|\n' '{print $2,$4,$6}' OFS=, RS= infile

thank you can not imagine if we can use regex as field separator,

sometimes the script is not working i check there is special character for each record set

# awk -vfs=',' 'BEGIN{printf "%s%s%s\n","Name"fs,"Address"fs,"Phone";}{
if($0!~/^ *$/) a[++x]=$NF;else b[x]=x-1};END{for(i=1;i<=x;i++)if(i-1==b&&b!=0||i==x)printf "%s\n",a;
else{printf "%s"fs,a}}' infile
Name,Address,Phone
Andi,none,82728
Peter,none,98799

regards
ygemici

1 Like

Yes, the previous solution only works if the empty line between the records is completely empty (two linefeeds).
Try this instead:

awk -F '=[ \t]*' '$1~/Name/{p=$2;if(getline)p=p OFS $2;if(getline)print p,$2}' OFS=, infile
1 Like

Thank you.. but i can got the wrong output and also did not work for Name field more than 1 word( ie. Andi ruby) and when the field has empty value

$ awk -V | head -1
GNU Awk 4.0.0

$ cat data.txt
   Name = Andi
Address = none
   Phone = 82728

   Name = Peter
Address = none
   Phone = 98799

$ awk -vfs=',' 'BEGIN{printf "%s%s%s\n","Name"fs,"Address"fs,"Phone";}{ \
if($0!~/^ *$/) a[++x]=$NF;else b[x]=x-1};END{for(i=1;i<=x;i++)if(i-1==b&&b!=0||i==x)printf "%s\n",a; \
else{printf "%s"fs,a}}' data.txt
Name,Address,Phone
Andi,none,82728,                                         ,Peter,none,98799

it's working , i tried to understand the code but can not get in.. i tried to modified for form that contain more than 3 fields ( name, address, phone,email etc.) but can not get the output it's only display the 3 fields.

1-)how about your input file?

# od -c input

2-) what is your system?

and
i modified code for other your requests(more than 1 word or empty)..
and i tried for gawk 4.0 but results are same as i think,
maybe your input file has contain different charset.

# cat testfile
Name =
Address = Oklahoma city
   Phone = 82728

   Name = Peter Surname
Address = none
   Phone = 98799

   Name = John
Address = NJ City
   Phone = 10000

   Name = Mr.Smith
Address =
   Phone = 5555555 555555


# gawk2 -V|grep "GNU AWK" -i
GNU Awk 4.0.0
# gawk2 -vfs=',' 'BEGIN{printf "%s%s%s\n","Name"fs,"Address"fs,"Phone";}
{if($0!~/^ *$/){s=gensub(".*=[\t ]*(.*)","\\1",$0);
if(match(s,"[^\t ]"))a[++x]=s;else a[++x]="XXX"}else b[x]=x-1}
END{for(i=1;i<=x;i++)if(i-1==b&&b!=0||i==x)printf "%s\n",a; else printf "%s"fs,a}' testfile
Name,Address,Phone
XXX,Oklahoma city,82728
Peter Surname,none,98799
John,NJ City,10000
Mr.Smith,XXX,5555555 555555