I am new to linux and I have two CSV files which are sorted and having the same number of rows.I wanted to join these two CSV files.

1.csv
1,2,3
4,5,6
7,8,9

2.csv
10,11,12
13,14,15
16,17,18

result.csv
1,2,3,10,11,12
4,5,6,13,14,15
7,8,9,16,17,18

I tried with cat 1.csv 2.csv >result.csv but in appends and not joins.Any help is appreciated.

share|improve this question
up vote 10 down vote accepted

Job for paste:

paste -d, {1,2}.txt

-d, sets the delimiter as ,. {1,2}.txt is brace expansion, done by shell, would be expanded to 1.txt 2.txt.


If you fancy a bit of awk:

awk 'NR==FNR {a[FNR]=$0; next} {print a[FNR], $0}' OFS=, {1,2}.txt
  • NR==FNR will be true only for the first file; {a[FNR]=$0; next} creates an array a with record numbers as keys, and records as the values

  • For the second file, {print a[FNR], $0} prints the array element at the corresponding line number followed by current record; OFS=, sets the output field separator as ,

Example:

$ cat 1.txt 
1,2,3
4,5,6
7,8,9

$ cat 2.txt 
10,11,12
13,14,15
16,17,18

$ paste -d, {1,2}.txt
1,2,3,10,11,12
4,5,6,13,14,15
7,8,9,16,17,18

$ awk 'NR==FNR {a[FNR]=$0; next} {print a[FNR], $0}' OFS=, {1,2}.txt
1,2,3,10,11,12
4,5,6,13,14,15
7,8,9,16,17,18
share|improve this answer
    
will this works when the csv 1.txt have fields with a newline inside? – 12431234123412341234123 10 mins ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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