Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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 *)
1
20
300

(* file 2 *)
4
50
600

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
add comment

2 Answers

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
add comment

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
add comment

Your Answer

 
discard

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.