Home > awk, bash > awk – Convert columns to rows

awk – Convert columns to rows

Problem:
You have a file with columns that you want to convert to rows.

From:

user@computer:~$less infile
field1 field2 field3
field1 field2
field1
field1 field2 field3 field4
...

To:

user@computer:~$less outfile
field1 field1 field1 field1
field2 field2 field2
field3 field3
field4

Solution:
awk

user@computer:~$ awk '{
      for (f = 1; f <= NF; f++)
         a[NR, f] = $f
   }
   NF > nf { nf = NF }
   END {
      for (f = 1; f <= nf; f++)
         for (r = 1; r <= NR; r++)
            printf a[r, f] (r==NR ? RS : FS)
   }' infile | tr -s " " " " | sed 's/^ //' > outfile

user@computer:~$less outfile
field1 field1 field1 field1
field2 field2 field2
field3 field3
field4

Source:
http://www.unix.com/unix-advanced-expert-users/188705-convert-column-data-row-data-using-shell-script.html
and
http://www.unix.com/78463-post3.html

Advertisements
Categories: awk, bash
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s