I'm running a scripts on a text file, and I want to merge its contents. Let's say that the file is called "file1".


This is some text, wow!

Now I have few versions after running scripts.


My<> is some text, wow!


Yours<> is some text, wow!


This is some txt<>, wow!

As you can see, some words are changed to another, and have <> added. Now I want to merge these files, so that the words are merged if they got changed:


My<>Yours<> is some txt<>, wow!

The order doesn't really matter; they just have to be merged. Is there tool that could make this easy?

  • contents should be merged from file1..4 ? and how you are deciding that which word will remain in final output file ? – Rahul Sep 7 '16 at 14:01
  • @Rahul, from what I understand, all changes are in final output and that the order doesn't matter.. for ex: My<>Yours<> could be Yours<>My<> instead – Sundeep Sep 7 '16 at 14:21
  • @Rahul yes, essentially files 2..4 have the same contents as file1, but some of the contents might be changed into word<>; we merge by the rule: if the word got changed in at least one file, merge the changed versions and replace old word with changed merged version. Thus, text -> txt<>, This -> My<>Yours<> (or, as noted, Yours<>My<>) and some -> some. We might merge files 1..4 or 2..4, doesn't matter; we won't need anything from file1(except for original order, if needed). – MatthewRock Sep 7 '16 at 14:25

I don't know any tools that would do that, but it's not hard to code. Here's a snippet of perl:

perl -E 'for $i (1..4) { open ($file,"<","file${i}"); { local $/; @{$words[$i]} = split " ",<$file>; }; close($file); }; for $i (0..scalar(@{$words[1]})-1) { $p=0; for $j (2..4) {  if ($words[1][$i] ne $words[$j][$i]) { print $words[$j][$i]; $p++ } } unless ($p) { print $words[1][$i] }; print " "; } print "\n"'

A lot of things could be improved, the first thing I would address if I had to use it would be the extra space at the end of the line, I would probably add the output words to an array and use the join function, but I find the task to strange to actually implement that.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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