Joining files together line by line in Linux

January 9th, 2009 | Categories: Linux | Tags:

Say you have a file called alpha.txt that contains

a
b
c

and another file called numbers.txt that contains

1
2
3

and you want to concatenate them together such that the resulting file reads

a 1
b 2
c 3

Of course this is a fairly trivial thing to do in any number of programming languages but I believe in not programming anything if I can possibly get away with it. With that in mind here is a standard Linux command (included in Ubuntu at least but probably in most other versions of Linux as well) that will do this for you.

paste alpha.txt nums.txt > joined.txt

By default, the paste command separates fields by tabs but you can easily change this with the -d switch. For example

paste alpha.txt num.txt -d , > joined.txt

results in a comma separated value (CSV) file

a,1
b,2
c,3

  1. January 10th, 2009 at 01:21
    Reply | Quote | #1

    Paste is part of GNU Coreutils and so should be on just about every modern unix-like system including mac osx.

  2. Prad Nelluru
    January 10th, 2009 at 04:44
    Reply | Quote | #2

    Any way to work this magic in Windows? I think Cygwin will work.

  3. January 10th, 2009 at 21:02
    Reply | Quote | #3

    Cygwin will work, but look into MSys too, likely less overhead but I’m not 100% since I’m not unfortunate enough as to have to use either.

  4. Ian Cottam
    March 29th, 2010 at 14:25
    Reply | Quote | #4

    Bit late posting a contribution to this one :-)
    I guess paste is fine these days, but you have always been able to do it since UNIX Version 1 (yes, v1) with: pr.
    -Ian

  5. March 29th, 2010 at 14:36
    Reply | Quote | #5

    It’s never too late Ian :)