how can I split a single column in several column of fixed dimension, for example I have a column like this:
1
2
3
4
5
6
7
8
and for size p. ex 4, I want to obtain
1 5
2 6
3 7
4 8
or for size p. ex 2, I want to obtain
1 3 5 7
2 4 6 8
how can I split a single column in several column of fixed dimension, for example I have a column like this:
1
2
3
4
5
6
7
8
and for size p. ex 4, I want to obtain
1 5
2 6
3 7
4 8
or for size p. ex 2, I want to obtain
1 3 5 7
2 4 6 8
Using awk:
If you know the desired output width you can use
column
.Note that above produces a CSV with the same number of fields in every row even when the number of input rows isn't an exact multiple of the desired number of output rows:
See https://stackoverflow.com/a/56725452/1745001 for how to do the opposite, i.e. generate a number of rows given a specified number of columns.
OK, this is a bit long winded and not infallible but the following should work:
Where
<cols>
is the number of rows you want andfile
is your input file. Explanation:Creates a temporary directory so that we can put temporary files into it. Store this in
td
- it's possible that your shell has atd
variable already but if you sub-shell for this your scope should be OK.Split the original file into many smaller file, each
<rows>
long. These will be put into your temp directory and all files will be prefixed withx
Write these files out so that the lines in consecutive columns
Remove the files and directory.
Clean the environment.
Assuming you know the number of rows in your column (here, 8):