How to merge two files line by line in Bash

BashUnix

Bash Problem Overview


I have two text files, each of them contains an information by line such like that

file1.txt            file2.txt
----------           ---------
linef11              linef21
linef12              linef22
linef13              linef23
 .                    .
 .                    .
 .                    .

I would like to merge theses files lines by lines using a bash script in order to obtain:

fileresult.txt
--------------
linef11     linef21
linef12     linef22
linef13     linef23
 .           .
 .           .
 .           .

How can this be done in Bash?

Bash Solutions


Solution 1 - Bash

You can use paste:

paste file1.txt file2.txt > fileresults.txt

Solution 2 - Bash

here's non-paste methods

awk

awk 'BEGIN {OFS=" "}{
  getline line < "file2"
  print $0,line
} ' file1

Bash

exec 6<"file2"
while read -r line
do
    read -r f2line <&6
    echo "${line}${f2line}"
done <"file1"
exec 6<&-

Solution 3 - Bash

Try following.

pr -tmJ a.txt b.txt > c.txt

Solution 4 - Bash

Check

man paste

possible followed by some command like untabify or tabs2spaces

Solution 5 - Bash

You can use paste with the delimiter option if you want to merge and separate two texts in the file

paste -d "," source_file1 source_file2 > destination_file

Without specifying the delimiter will merge two text files using a Tab delimiter

paste source_file1 source_file2 > destination_file

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsemteuView Question on Stackoverflow
Solution 1 - BashMark ByersView Answer on Stackoverflow
Solution 2 - Bashghostdog74View Answer on Stackoverflow
Solution 3 - BashvthaView Answer on Stackoverflow
Solution 4 - BashChristopher CreutzigView Answer on Stackoverflow
Solution 5 - BashManyam Nandeesh ReddyView Answer on Stackoverflow