I have a file with 25 matrices in a file, and each matrix is has 128 rows and 5 columns. Each matrix are putted one after the other, in a vertical way. Like this

File input(file1):


I want to put each array in a horizontal way. Like this(file2)

Array1  Array2  Array3 ... Array25

I tried to use this command :

pr -25t -w 4000 file1 > file2

But is not working as I want.

  • 3
    Could you clarify your "Array" examples? What you show is just strings. The actual input/output you show could be handled with tr '\n' ' ' <file1 >file2 but I don't think that's what you want. (Or is it?) – Wildcard Jun 8 '16 at 3:22
  • A KISS approach might be to split into 25 individual files e.g. split -l128 file1 and then re-assemble them using paste e.g (assuming the default split prefix, and brace expansion) paste xa{a..y} > file2 – steeldriver Jun 8 '16 at 4:19
  • @steeldriver, it works!. – alloppp Jun 8 '16 at 11:26

Let's consider this test file with arrays with 3 rows each:

$ cat File
1 2
3 4
5 6
a b
c d
e f

Now, let's concatenate the arrays:

$ awk -v nr=3 '{a[NR]=$0} END{for (i=1;i<=nr;i++) {for (j=i;j<=NR;j+=nr) printf "%s ",a[j]; print""}}' File
1 2 a b A B 
3 4 c d C D 
5 6 e f E F 

In your data file, there are 128 rows per array. In that case, run:

awk -v nr=128 '{a[NR]=$0} END{for (i=1;i<=nr;i++) {for (j=i;j<=NR;j+=nr) printf "%s ",a[j]; print""}}' File

How it works

  • -v nr=128

    This sets the variable nr to the number of rows per array.

  • a[NR]=$0

    NR is the line number. We save each row (line) in the array a.

  • END{for (i=1;i<=nr;i++) {for (j=i;j<=NR;j+=nr) printf "%s ",a[j]; print""}}

    After we have read in all the rows, this writes them out again in the form that you want.

    To do this, we loop over the variable i starting with i=1 and finishing with i=nr. For each i, we print the new row i. For each i value, we loop over j where j is the number of row of the old file that belongs on row i of the new file`.


Although it makes it more difficult for a beginner to read, a ternary statement can be used to give a slight improvement in the formatting:

$ awk -v nr=3 '{a[NR]=$0} END{for (i=1;i<=nr;i++) for (j=i;j<=NR;j+=nr) printf "%s%s",a[j],(j+nr<=NR?" ":"\n")}' File
1 2 a b A B 11 22
3 4 c d C D 33 44
5 6 e f E F 55 66

j+nr<=NR?" ":"\n" is a ternary statement. It returns a space if j+nr<=NR. Otherwise, it returns a newline.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.