tashuhka
tashuhka

Reputation: 5126

Merge two csv files and add a counter

I want to merge two csv files with the same number of rows and add a counter in the first column. For example, for the two input files:

f1.csv

a, b, c
d, e, f

f2.csv

aa, bb
dd, ee

I want to generate a file f.csv with

1, a, b, c, aa, bb
2, d, e, f, dd, ee

I have tried with:

awk '{for(i=0;i<2;i++){print ",", i, $1, $2}}' f1.csv f2.csv > f.csv

But it generates something like this:

1, a, b, c
2, d, e, f
1, aa, bb
2, dd, ee

Any hint?

Upvotes: 0

Views: 57

Answers (2)

Jotne
Jotne

Reputation: 41460

Here is an awk

awk 'FNR==NR {a[NR]=$0;next} {print FNR", "a[FNR]", "$0}' f1 f2
1, a, b, c, aa, bb
2, d, e, f, dd, ee

Upvotes: 3

Avinash Raj
Avinash Raj

Reputation: 174874

Through paste and awk,

$ paste -d", " file1 /dev/null file2 | awk '{print NR", "$0}'
1, a, b, c, aa, bb
2, d, e, f, dd, ee

Upvotes: 3

Related Questions