1

I have a matrix:

input.txt
1 2 3
2 3 5
2 3 4

~
I would like to write it in one column as

output.txt
1 
2 
2 
2
3
3
3
5
4

I can do it with the following script

#!/bin/sh
pr -ts" " --columns 3 input.txt > output.txt
awk '
{ 
    for (i=1; i<=NF; i++)  {
        a[NR,i] = $i
    }
}
NF>p { p = NF }
END {    
    for(j=1; j<=p; j++) {
        str=a[1,j]
        for(i=2; i<=NR; i++){
            str=str" "a[i,j];
        }
        print str
    }
}' output.txt

But I am looking for an efficient way to do it for a matrix with n columns.

The script pr -ts" " --columns 50 input.txt > output.txt is also not working for larger column size. I used it with 50 column size and got the following error

pr: page width too narrow
Kay
  • 1,957
  • 2
  • 24
  • 46
  • 1
    `awk '...' input.txt | fmt -1` or just `awk '...' input.txt` replacing `" "` with `OFS` – jhnc Jul 22 '19 at 00:53

1 Answers1

1

Is this what you're trying to do?

$ cat tst.awk
{
    for (i=1; i<=NF; i++) {
        vals[i] = vals[i] $i ORS
    }
}
END {
    for (i=1; i<=NF; i++) {
        printf "%s", vals[i]
    }
}

$ awk -f tst.awk file
1
2
2
2
3
3
3
5
4
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
  • 1
    Thanks. It worked. But I see some ^M. I think i need to make some formatting. – Kay Jul 22 '19 at 01:23
  • 1
    Your input must contain ^Ms then so see https://stackoverflow.com/q/45772525/1745001 for how to handle that. – Ed Morton Jul 22 '19 at 01:24