5

This question already has an answer here:

I have two files:

file1 contains:

1
2
3
4

file2 contains:

John
Sam
George
Ken

I want to combine these files to create one file(file3)

1, John
2, Sam
3, George
4, Ken

My thought was to use nested loops and add the comma for each line,

for x in file1
do
echo "$x" >> file3
for y in file2
echo ",$y" >> file3
done
done

Is there a command I need to use? How do I get it to x and y to appear on one line for each entry in both files?

marked as duplicate by don_crissti, umläute, derobert, slm Apr 22 '15 at 20:22

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

5

You can use paste:

$ :|paste -d',' file1 - | paste -d' ' - file2
1, John
2, Sam
3, George
4, Ken

or:

$ :|paste -d', ' file1 - file2
  • what about without the space? something like: $ :|paste -d',' file1 - | paste - file2 1, John 2, Sam 3, George 4, Ken – Juan Davila Apr 22 '15 at 15:47
  • you will get tab character instead of space, paste default delimiter is tab. – cuonglm Apr 22 '15 at 15:51
  • I also I thought this might work too? paste -d file1 file2 >> file3\ 1,John 2,Sam 3,George 4,Ken – Juan Davila Apr 22 '15 at 15:54
  • No, it didn't. You can read the paste command manual I gave in my answer. – cuonglm Apr 22 '15 at 15:58
3

Another paste solution

paste -d ', ' file1 /dev/null file2
1, John
2, Sam
3, George
4, Ken
  • Or maybe shorter :|paste -d', ' file1 - file2 – cuonglm Apr 22 '15 at 16:10
  • Nice one. I didn't realize that delimiters can be changed for each successive file – Peter.O Apr 22 '15 at 16:11
  • What is hypen(-) utilized for in this situation? – Juan Davila Apr 22 '15 at 16:14
  • 1
    @JuanDavila: the hypen tells paste to take the "file" from stdin instead of from an actual "file" – Peter.O Apr 22 '15 at 16:17
  • 1
    @JuanDavila: :| is a no-op. – cuonglm Apr 22 '15 at 16:23
1

you could try this:

paste -d, file1 file2 > file3

output (file3):

1,John
2,Sam
3,George
4,Ken
  • Okay, that seems to legit. I suppose the hyphen has some meaning in the paste command as well? – Juan Davila Apr 22 '15 at 16:13
  • @JuanDavila, it's a common convention for *nix commands to take command-line options that change or specify behavior. -d is one such flag. Reading man paste will show you exactly what it does. – HalosGhost Apr 22 '15 at 16:24
1
sed 's/$/, /' file1 | paste -d '\0' - file2

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