user3784040
user3784040

Reputation: 111

merge contents of two files into one file in bash

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

Upvotes: 7

Views: 14422

Answers (5)

Ed Morton
Ed Morton

Reputation: 203522

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

Upvotes: 2

Sridhar Nagarajan
Sridhar Nagarajan

Reputation: 1105

while read line1 && read -u 3 line2
do 
    printf "$line1\n" >> File3
    printf "$line2\n" >> File3
done < File1 3<File2

you can use file descriptors, to read from two files and print each line to the out file.

Upvotes: 0

Jake Cobb
Jake Cobb

Reputation: 1861

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.

Upvotes: 1

Marco Baldelli
Marco Baldelli

Reputation: 3728

$ 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

Upvotes: 2

shauryachats
shauryachats

Reputation: 10385

You can always use paste command.

paste -d"\n" File1 File2 > File3

Upvotes: 13

Related Questions