2

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".

file1:

This is some text, wow!

Now I have few versions after running scripts.

file2:

My<> is some text, wow!

file3:

Yours<> is some text, wow!

file4:

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:

Output:

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?

3
  • contents should be merged from file1..4 ? and how you are deciding that which word will remain in final output file ?
    – Rahul
    Commented Sep 7, 2016 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
    Commented Sep 7, 2016 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). Commented Sep 7, 2016 at 14:25

1 Answer 1

3

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .