Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

In Emacs/Xemacs, there is a rectangle feature, such that you can delete, copy, etc., "rectangles" of text.

Now suppose I have two text files, each containing one column of numbers. Is it possible to use Mathematica to "paste" the columns of text, side by side (perhaps separated by at least one space)?

For example, suppose I have two text files:

(* file 1 *)

(* file 2 *)

I would like to be able to obtain a single text file like this:

(* file 3 *)
1   4
20  50
300 600

Do you have any ideas of how I can do this efficiently? The ideas I have (like stripping and joining row-by-row, and adding the appropriate number of spaces) are really complicated, and I feel like there must be an easier way. Thanks!

share|improve this question
up vote 11 down vote accepted

I think you can just do this:

file1dat = Import["file1.txt", "Table"];
file2dat = Import["file2.txt", "Table"];
file3dat = Import["file3.txt", "Table"];
Export["output.txt", Join[file1dat, file2dat, file3dat, 2]];

Edit: Here's a better solution, which will place the entire lines of text (regardless of whether there is whitespace within a line) next to each other, separated by one space. You can change the Riffle call to put whatever character you like between the strings:

files = {"file1.txt", "file2.txt", "file3.txt"};
Export["output.txt", Transpose@{StringJoin@Riffle[#, " "] & /@
    Transpose[StringSplit[Import[#, "Text"], "\n"] & /@ files]}, "Table"]
share|improve this answer
Thank you so much! You made my day! – Andrew May 17 '12 at 1:21

If you are on Linux then this is an option:

$paste file?.txt > output.txt

Just use paste to join the files together.

Which in Mathematica speak is:

Run["paste file?.txt > output.txt"]
share|improve this answer

Your Answer


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.