awk - list to tables

Hello there,

I have large tab-delimitated lists (see input file) and I need to convert it into tab-delimitated tables (see output file). I would like to do it with an awk script. Any ideas?

Input file:
header1 <tab> a <tab> a <tab> a <tab> a . . .
header2 <tab> b <tab> b <tab> b <tab> b . . .
header3 <tab> c <tab> c <tab> c <tab> c . . .
header4 <tab> d <tab> d <tab> d <tab> d . . .
. . .

Output file:
header1 <tab> header2 <tab> header3 <tab> header4 . . .
a <tab> b <tab> c <tab> d . . .
a <tab> b <tab> c <tab> d . . .
a <tab> b <tab> c <tab> d . . .
a <tab> b <tab> c <tab> d . . .
. . .

Somebody posted a matrix transform a few weeks back, search for that term? Not sure if it would work here but worth a shot.

awk '{
  for(f=1; f<=NF; f++)
      r2c[f","NR] = $f
} END {
  for(f=1; f<=NF; f++) {
    for(row=1; row<=NR; row++)
      printf("%s\t", r2c[f","row])
    print ""
  }
}' file

Dear shamrock,

Thanks for the help - I have problems to execute the script.
I'm not sure it the problem is the $1 at the end?

./r2c.sh file.input

###########################

#!/bin/bash

awk '
{
for(f=1; f<=NF; f++)
r2c[f","NR] = $f
} END {
for(f=1; f<=NF; f++) {
for(row=1; row<=NR; row++)
printf("%s\t", r2c[f","row])
print ""
}
}' $1

#########################

Yep, that's the problem, where you declare $1? :slight_smile:

Show the error you are getting.

I tried your version of the script with the following ending:

...}' file

executing the script with: r2c.sh

---

and I tried the following ending:

...}' $1

executing the script with: r2c.sh file

But nothing happens.

Hi mens, it really helpful, I did it and Works OK!:
cat code.ksh

#! /usr/bin/ksh
awk '{
for(f=1; f<=NF; f++)
r2c[f","NR] = $f
} END {
for(f=1; f<=NF; f++) {
for(row=1; row<=NR; row++)
printf("%s\t", r2c[f","row])
print ""
}
}' $1

./code <file.txt> ... and voila!
Thanks shamrock

Lobaria: can you check whether NF and NR are defined in the END part? Just add a print statement. My hunch is that they will be zero in your version of awk.

Do you have nawk, or mawk, or gawk, or XPG4 awk on your system? Then try with one of those instead.

Modding the script so that it remembers the last values of NR and NF before the END section is not a complicated fix, as such.

Dear era, dear shamrock,

Thanks - Problem solved !
I was thinking along the same lines and installed gawk and it worked just fine.

Does anybody have an idea what the problem could be with my version of awk?

######################
### gawk script (r2c.sh)
### Converts rows into columns
######################

#! /bin/sh

gawk '{
for(f=1; f<=NF; f++)
r2c[f","NR] = $f
} END {
for(f=1; f<=NF; f++) {
for(row=1; row<=NR; row++)
printf("%s\t", r2c[f","row])
print ""
}
}' $1

##########################

Well, my speculation would be that it doesn't remember the NF and NR values in END, since strictly speaking they are no longer defined in that context (intuitively speaking, at least).