Merge alternate lines from two files

File1:

.tid.setnr := 1123 
.tid.setnr := 3345 
.tid.setnr := 5431
.tid.setnr := 89323

File2:

.tid.info := 12
.tid.info := 3
.tid.info := 44
.tid.info := 60

Output file:

.tid.info := 12
.tid.setnr := 1123
.tid.info := 3
.tid.setnr := 3345
.tid.info := 44
.tid.setnr := 5431
.tid.info := 60
.tid.setnr := 89323

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Using paste:

paste -d \n file2 file1

Method 2

Another awk solution:

awk '{print; getline < "file1"; print}' file2

Method 3

The paste solution is the most portable and most efficient. I’m only mentioning this alternative in case you prefer its behaviour in the case where the two files don’t have the same number of lines:

With GNU sed:

sed Rfile1 file2

If file1 has fewer lines than file2, then when file1 is exhausted, sed will not output anything for it (as opposed to empty lines for paste).

If file1 has more lines than file2, then those extra lines will be discarded (as opposed to printing empty lines for file2 with paste).

$ paste a b
1       a
2       b
3
4
$ paste -d \n a b
1
a
2
b
3

4

$ sed Rb a
1
a
2
b
3
4
$ sed Ra b
a
1
b
2

Method 4

Using awk (gawk, nawk, mawk):

awk 'NR==FNR {x[FNR]=$0;next} {print x[FNR]"n"$0}' file2 file1 > outputfile
  • NR==FNR {x[FNR]=$0;next}: NR==FNR is matched only if the current record number is equal to the current file record number (hence it’s matched only while processing the first file): stores the currently processed record into the array x at an index equal to the current file record number and skips the current record
  • {print x[FNR]"n"$0}: prints the content of the array x at an index equal to the current file record number followed by a newline and by the content of the current record
~/tmp$ cat file1
.tid.setnr := 1123
.tid.setnr := 3345
.tid.setnr := 5431
.tid.setnr := 89323
~/tmp$ cat file2
.tid.info := 12
.tid.info := 3
.tid.info := 44
.tid.info := 60
~/tmp$ awk 'NR==FNR {x[FNR]=$0;next} {print x[FNR]"n"$0}' file2 file1
.tid.info := 12
.tid.setnr := 1123
.tid.info := 3
.tid.setnr := 3345
.tid.info := 44
.tid.setnr := 5431
.tid.info := 60
.tid.setnr := 89323

Method 5

The easiest solution is given below.

cat file1 >> file2

or

cat file2 >> file1


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x