Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert single column file into multiple columns

Basically, I want to convert one column file into multiple column file specified by number of rows.

I do not want to reinvent the wheel. I want to make sure if there is a unix command / or standard way of doing this before writing a custom script.

For example, let's say I have the following file:

$cat input.txt
tom
jack
kim
bart
foo
bar

I want to turn this into 3 row file

$ cat input.txt | my_script --every=3 --delimiter=tab
tom bart
jack foo
kim bar

or 2 row file with the different delimter:

$ cat input.txt | my_script --every=2 --delimiter=,
tom,kim,foo
jack,bart,bar
like image 302
Alby Avatar asked Nov 29 '22 00:11

Alby


2 Answers

What about using xargs?

two records per line:

$ xargs -n2 < file
tom jack
kim bart
foo bar

three records per line:

$ xargs -n3 < file
tom jack kim
bart foo bar
like image 57
fedorqui 'SO stop harming' Avatar answered Dec 05 '22 17:12

fedorqui 'SO stop harming'


You can use paste command in UNIX for converting the file into multiple columns. By default, tab is the delimiter. To change the delimiter, use -d option

Command: convert one column file into two columns

paste - - < input.txt

output:

tom  bart 
jack foo 
kim  bar

Command: convert one column file into two columns with , as a delimiter

paste - - -d, < input.txt

Output:

tom,bart 
jack,foo 
kim,bar
like image 41
Shabbir Burhanpurwalla Avatar answered Dec 05 '22 19:12

Shabbir Burhanpurwalla