6

I am looking for a simple line of code (if possible) to simply merge two files column wise and save the final result into a new file.

Edited to response to the first answer @heitor:

By using paste file1.csv file2.csv, What happened is:

For instance file 1:

A B
1 2

file2:

C D
3 4

By doing paste -d , file1.csv file2.csv >output.csv I got

 A B
 C D
 1 2
 3 4

not

A B C D
1 2 3 4

By doing cat file1.csv file2.csv I got

A B 
1 2
C D
3 4

Neither of them is what I want. Any idea?

Any idea?

xiahfyj
  • 101
  • 1
  • 5
  • I see your files are space separated, you should use `-d " "` to join them. Also, that's very weird, I've just tried the same inputs and got the expected result – heittpr May 30 '20 at 06:19

2 Answers2

7

Use paste -d , to merge the two files and > to redirect the command output to another file:

$ paste -d , file1.csv file2.csv > output.csv

E.g.:

$ cat file1.csv
A,B

$ cat file2.csv
C,D

$ paste -d , file1.csv file2.csv > output.csv

$ cat output.csv
A,B,C,D

-d , tells paste to use , as the delimiter to join the columns.

> tells the shell to write the output of the paste command to the file output.csv

heittpr
  • 591
  • 4
  • 9
2

Indeed using paste is pretty simple,

$ cat file1.csv 
A B
1 2

$ cat file2.csv 
C D
3 4

$ paste -d " " file1.csv file2.csv 
A B C D
1 2 3 4

With the -d option I replaced the default tab character with a space.

Edit:

In case you want to redirect that to another file then,

paste -d " " file1.csv file2.csv > file3.csv
$ cat file3.csv 
A B C D
1 2 3 4
Themelis
  • 4,048
  • 2
  • 21
  • 45
  • I opened the file with a csv-viewer online and it works as expected, take a look https://www.convertcsv.com/csv-viewer-editor.htm – Themelis May 29 '20 at 23:43