How to Merge Files Without Using Merge

I use a Mac almost exclusively for development. Mac doesn’t come with the Linux merge command and sometimes I need to merge text files. It’s pretty easy to do using diff and grep.

I’m going to show you how to merge the changes from two files into one.

I’ll use file1, file2, file3 and file4 as the end product.

diff -DVERSION1 file1 file2 > file3

This commend puts all of changes from file1 and file2 into file3. Open file3 in a text editor. You will see stuff like this.

#ifdef VERSION1
// I updated the comment in file, but it doesn't conflict with file2 so it looks like this

If there is a conflict between file1 and file2, it might look like this.

#ifdef VERSION1
// I updated the comment to fix a typo
#else /* VERSION1 */
// I updated the coment to fix a type
#endif /* VERSION1 */

I then go through file3, searching for ‘#else’ and resolve those conflicts. I generally consider file1 to be the authority, so I usually remove the #else leaving the #if part.

Then when I’m done resolving conflicts, I run this.

grep -v '^#if' file3 | grep -v '^#endif' > file4

Now file4 has all of the correct changes from file1 and file2.

Share Button