2

I need to merge the contents of two folders sequentially into individual destinations. Here is what i have. A,B,C,D,E,F are individual files.

Folder 1:
A
B
C
...

Folder 2:
D
E
F
...

At the output i need merged files sequentially. So they should be merged like this:

Output:
AD
BE
CF
...

In other words, first file from the Folder 1 with the first file from the Folder 2. Second file from the Folder 1 with the second file from the Folder 2. In our case AD is consisting of the content of files A and D, BE consisting of files B and E, etc.

Both folders have the same number of files. Output can go anywhere. For the sake of simplicity let's call it Output folder and locate it in the same root as Folder 1 and 2.

Been looking for the solution for two days now. Yikes!

  • 1
    Are they text files? – mchid Sep 17 '19 at 23:14
  • Content is binary. Steeldriver submitted the SOLUTION. I hope others will find it as useful. This was never asked before. It is most handy tool when you need to add a certain pre made "binary tail" to a bunch of binary files, and merge the result. – dsolaris Sep 18 '19 at 10:18
1

Assuming that by "merge" you mean concatenate the files' contents, you could do something like this:

#!/bin/bash

while IFS= read -r -d '' -u3 file1 && IFS= read -r -d '' -u4 file2; do 
  cat "$file1" "$file2" > "${file1##*/}${file2##*/}"
done 3< <(printf '%s\0' "Folder 1"/*) 4< <(printf '%s\0' "Folder 2"/*)

This will create files in the current directory, whose name is the concatenation of the two constituent filenames. It assumes that you want to merge files in the order in which they sort in your locale. The null delimiters make it safe for any legal filenames (which may be overkill for your application).

  • This is EXACTLY what i was looking for. You even added the bonus of merging file names which adds valuable info to the file. Voted up. – dsolaris Sep 18 '19 at 10:16

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.