Skip to content
Advertisement

How can I merge two files in one using BASH or Python script?

We assume that I have two files like this:

File1 :

JavaScript

File2 :

JavaScript

I want to combine them in order to get one file with this output file :

OuputFile :

JavaScript

So, in Windows, I made this batch file to get what I expected, but, I have no idea how to do it in BASH (Bourne-Again shell) or in Python script.

The Batch File :

JavaScript

Advertisement

Answer

A Bash solution

JavaScript

This loops over file1, and for each line of file1 loops over file2. The printf line assembles the output, and the parameter expansion for line removes the leading F: .

Result:

JavaScript

A solution with join and sed

This would work as well:

JavaScript

This is a slight abuse of join. -j 50 says to join on matching field number 50, which doesn’t exist and is thus considered equal for all lines, resulting in the Cartesian product of the two files:

JavaScript

To get the lines into proper order, we specifiy the output format with -o 2.1,1,1. Because the default field delimiter is whitespace, we specify a character that is not contained in the input as the new delimiter with -t '~':

JavaScript

And finally, we replace ~F: with a space on each line and prepend C: using sed:

JavaScript

If the order of the lines doesn’t matter, this can be slightly shortened to

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement