awk sed help

$cat log.txt
#fld names
#Fld: Name Age Sex Lcation

CC 25 M XYZ
BB 21 F XAS
SD 21 M AQW

Output required:

Fld	rec1	rec2	rec3
Name	CC	BB	SD
Age	25	21	21
Sex	M	F	M
Lcation XYZ 	XAS 	AQW

I tried this

$ sed -e '/^$/d' -e '/^#fld/d' -e 's/#Fld: //' log.txt | awk '{
for(j=1;j<=NF;j++)
{arr[j]=arr[j]"\t"$j}
}
END {for(i in arr)
print arr}
'


        Name    CC      BB      SD
        Age     25      21      21
        Sex     M       F       M
        Lcation XYZ     XAS     AQW

But I am unable to append the header line as I wanted.

Please help.

Not a very elegant solution, but you could try:

#!/usr/bin/perl
# show_records.pl
use strict;
use warnings;
my (@names, @ages, @sexes, @locations);
while (<>) {
    next  if (m/^\s*#/);    # Skip comments
    next  if (m/^$/);        # Skip empty lines
    my ($name, $age, $sex, $location) = split(/\s+/, $_);
    push (@names, $name);
    push(@ages, $age);
    push(@sexes, $sex);
    push(@locations, $location);
}
print "Fld\t";
my $i=0;
while ($i <= $#names) {
    print "rec", ++$i, "\t";
}
print "\nName\t", join("\t", @names), "\n";
print "Age\t", join("\t", @ages), "\n";
print "Sex\t", join("\t", @sexes), "\n";
print "Location\t", join("\t", @locations), "\n";

run this perl script as:

perl show_records.pl log.txt

Just add this:

$ sed -e '/^$/d' -e '/^#fld/d' -e 's/#Fld: //' log.txt | awk '
BEGIN{print "\tFld\trec1\trec2\trec3"}
{
for(j=1;j<=NF;j++)
{arr[j]=arr[j]"\t"$j}
}
END {for(i in arr)
print arr}
'

Just few corrections, insert row's before shifting.

$ sed -e '/^$/d' -e '/^#fld/d' -e 's/#Fld: //' log.txt | awk '
BEGIN{FS=" ";OFS="\t"}
NR==1{$0="Fld "$0}
NR>1 {$0="rec"(NR-1)" "$0}
{for(i=1;i<=NF;i++) rc[i","NR]=$i}
END  {
for(i=1;i<=NF;i++)
{
for(r=1; r<=NR; r++)
printf("%s\t", rc[i","r]);print ""
}}'

Thanks all. It worked perfectly.