SweetCode
SweetCode

Reputation: 25

Joining two file with sed awk separated by comma

I have two files.

file1.txt

example1
example2
example3

file2.txt

testing1
testing2
testing3

I am trying to join the values from these two files into a new comma separated file, with output

desired output

example1,testing1
example2,testing2
example3,testing3

Could anyone help to do this in awk/sed ? thank you

Upvotes: 2

Views: 4128

Answers (3)

anubhava
anubhava

Reputation: 784968

You can just use paste:

paste -d, file1 file2
example1,testing1
example2,testing2
example3,testing3

Or, you can use awk:

awk -v OFS=, 'FNR==NR{a[++i]=$0; next} {print a[FNR], $0}' file1 file2
example1,testing1
example2,testing2
example3,testing3

Upvotes: 6

Akshay Hegde
Akshay Hegde

Reputation: 16997

You can also use pr other than paste command

[akshay@localhost tmp]$ cat file1
example1
example2
example3

[akshay@localhost tmp]$ cat file2
testing1
testing2
testing3

[akshay@localhost tmp]$ pr -mtJS',' file1 file2
example1,testing1
example2,testing2
example3,testing3

Upvotes: 0

potong
potong

Reputation: 58371

This might work for you (GNU sed):

sed 'Rfile2' file1 | sed 'N;y/\n/,/'

The first sed script reads a line from file1 then a line from file2. The second script takes this output and reads two lines at a time replacing the newline between the lines by a comma.

N.B. This expects each file1/2 to be the same length.

Upvotes: 0

Related Questions