8

I have two files :

f1:                                      f2:
==============                         ===============
some text line 1                       A1
some text line 2                       A2
some text line 3                       A3

can I quickly merge these two files to produce f3:

some text line 1
A1
some text line 2
A2
some text line 3 
A3
рüффп
  • 1,677
  • 4
  • 27
  • 35
Forever Learner
  • 729
  • 1
  • 10
  • 17

3 Answers3

20

It's a job for paste:

paste -d'\n' f1.txt f2.txt

Example:

$ cat foo.txt 
some text line 1
some text line 2
some text line 3

$ cat bar.txt 
A1
A2
A3

$ paste -d'\n' foo.txt bar.txt 
some text line 1
A1
some text line 2
A2
some text line 3
A3
heemayl
  • 54,820
  • 8
  • 124
  • 141
  • Wow, I was not aware there is delimiter option for the paste as well. I thought of paste but it combined the contents on the same line. Thank you for your help and quick response. +1 – Forever Learner Jun 07 '16 at 09:18
  • 1
    awesome, I was gonna click on `post your answer` and saw `1 answer` ;) – Rahul Jun 07 '16 at 09:19
3

Yes, you can do this using one while loop and read through the two files using read.

#!/bin/sh

while read file1 <&3 && read file2 <&4
do
    printf "%s\n" "$file1" >> mergedFile.txt
    printf "%s\n" "$file2" >> mergedFile.txt
done 3</path/to/file1/file1.txt 4</path/to/file2/file2.txt

You can use echo instead of printf. The results are in mergedFile.txt If the files you are processing are not huge, perhaps the above is easier and more portable than most solutions.

sentifool
  • 39
  • 8
1

POSIX Awk; this works with an arbitrary amount of files, and the files don’t even have to have the same amount of lines. The script keeps going until all files are out of lines:

BEGIN {
  do {
    br = ch = 0
    while (++ch < ARGC)
      if (getline < ARGV[ch]) {
        print
        br = 1
      }
  } while (br)
}
Zombo
  • 1
  • 5
  • 43
  • 62