7

This question already has an answer here:

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

marked as duplicate by don_crissti, cuonglm, Scott, dr01, cas Jun 8 '16 at 8:14

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • === is part of the file ? – Rahul Jun 7 '16 at 9:15
  • No . " === " was just used as separator for showing the file contents – Forever Learner Jun 7 '16 at 9:16
19

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
  • 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 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.

  • 1
    You can also put the append redirection on the "done" line instead of inside the while block – glenn jackman 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' ? – someonewithpc 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.