merge contents of two files into one file in bash

11,558

Solution 1

You can always use paste command.

paste -d"\n" File1 File2 > File3

Solution 2

paste is the way to go for this, but this alternative can be a useful approach if you ever need to add extra conditions or don't want to end up with blank lines when one file has more lines than the other or anything else that makes it a more complicated problem:

$ awk -v OFS='\t' '{print FNR, NR, $0}' file1 file2 | sort -n | cut -f3-
Line1file1
Line1file2
Line2file1
Line2file2
line3file1
line3file2
line4file1
line4file2

Solution 3

$ cat file1
Line1file1
Line2file1
line3file1
line4file1

$ cat file2
Line1file2
Line2file2
line3file2
line4file2

$ paste -d '\n' file1 file2 > file3

$ cat file3
Line1file1
Line1file2
Line2file1
Line2file2
line3file1
line3file2
line4file1
line4file2

Solution 4

In Linux:

grep -En '.?' File1 File2 | sed -r 's/^[^:]+:([^:]+):(.*)$/\1 \2/g' \
    | sort -n | cut -d' ' -f2- > File3

If you're on OS X, use -E instead of -r for the sed command. The idea is this:

  1. Use grep to number the lines of each file.
  2. Use sed to drop the file name and put the line number into a space-separated column.
  3. Use sort -n to sort by the line number, which is stable and preserves file order.
  4. Drop the line number with cut and redirect to the file.

Edit: Using paste is much simpler but will result in blank lines if one of your files is longer than the other, this method will only continue with lines from the longer file.

Share:
11,558
user3784040
Author by

user3784040

Updated on June 08, 2022

Comments

  • user3784040
    user3784040 almost 2 years

    I have two files which has following contents

    File1

    Line1file1
    Line2file1
    line3file1
    line4file1
    

    File2

    Line1file2
    Line2file2
    line3file2
    line4file2
    

    I want to have these file's content merged to file3 as

    File3

    Line1file1
    Line1file2
    Line2file1
    Line2file2
    line3file1
    line3file2
    line4file1
    line4file2
    

    How do I merge the files consecutively from one file and another file in bash?

    Thanks