1

I have an out put from R and I need to print the out put properly. I need to print odd and even rows as respective columns.

Original file

4             4             4             4             4 
-3.592311e+00 -3.360352e+00 -3.063397e+00 -3.660137e+00  8.053911e+00 
            4             4             4             4             4 
 1.077868e+01 -2.455155e+00  6.214082e+00  5.311552e+00  5.311552e+00
       10            10            10            10            10 
-4.394679e+00 -2.527588e+00  7.716434e+00  5.001199e+00  2.653916e+00 
           10            10            10            10            10 
 3.673181e+00  3.721885e+00  3.464234e+00 -4.363173e-01  6.849429e-01

Desired output

    4 -3.592311e+00
    4 -3.360352e+00
    4 -3.063397e+00
    4 -3.660137e+00
    4 8.053911e+00
    4 1.077868e+01
    4 -2.455155e+00
    4 6.214082e+00
    4 5.311552e+00
    4 5.311552e+00
   10 -4.394679e+00
   10 -2.527588e+00
   10 7.716434e+00
   10 5.001199e+00
   10 2.653916e+00 
   10 3.673181e+00
   10 3.721885e+00 
   10 3.464234e+00
   10 -4.363173e-01
   10 6.849429e-01

I used the following code but it couldn't give me what i want

awk '{ for (i = 1; i <= NF; i++) f[i] = f[i] " " $i ; if (NF > n) n = NF } END { for (i = 1; i <= n; i++) sub(/^ */, "", f[i]) ; for (i = 1; i <= n; i++) print f[i] } ' file

1 Answer 1

1

Here's an awk approach, which relies on splitting even and odd lines into appropriate arrays.

$ awk 'NR%2 !=0 {split($0,col1)}; NR%2 == 0 {split($0,col2); for (i=1;i<=length(col1);i++) print col1[i],col2[i]};' inpu>
4 -3.592311e+00
4 -3.360352e+00
4 -3.063397e+00
4 -3.660137e+00
4 8.053911e+00
4 1.077868e+01
4 -2.455155e+00
4 6.214082e+00
4 5.311552e+00
4 5.311552e+00
10 -4.394679e+00
10 -2.527588e+00
10 7.716434e+00
10 5.001199e+00
10 2.653916e+00
10 3.673181e+00
10 3.721885e+00
10 3.464234e+00
10 -4.363173e-01
10 6.849429e-01

The way this works is quite simple. NR % 2 != 0 tells us that the line is odd, and NR % 2 == 0 is even. In odd lines we only split the whole line into array. In even lines, we split and print out both arrays on item-by-item basis. This process repeats in alternating fashion till the last line is reached.

This can be improved, of course, space between columns can be increased and such. The approach isn't bulletproof and is tailored to this specific case, where number of fields is the same in each line of the original file

1
  • 1
    NIce answer. To simplify a bit: awk '{split($0,col1); getline; for (i=1; i<=NF; i++) print col1[i], $i}' Commented Jan 17, 2017 at 14:14

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.