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
2
  • === is part of the file ?
    – Rahul
    Jun 7 '16 at 9:15
  • No . " === " was just used as separator for showing the file contents Jun 7 '16 at 9:16
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
2
  • 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 Jun 7 '16 at 9:18
  • 1
    awesome, I was gonna click on post your answer and saw 1 answer ;)
    – Rahul
    Jun 7 '16 at 9: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.

4
  • 1
    You can also put the append redirection on the "done" line instead of inside the while block Jun 7 '16 at 15:41
  • +1: paste is a better fit for this question, but this is a great example of using extra file descriptors.
    – alexis
    Jun 7 '16 at 16:27
  • This will stop when file1 ends. Perhaps || would be better?
    – chx
    Jun 7 '16 at 20:05
  • What is the '<&3' ? Jun 8 '16 at 6:34
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)
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.