Home > Software engineering >  Merge two files line by line in shell
Merge two files line by line in shell

Time:11-20

I have two files and I want to merge them in one but line by line

file1 :
1
2
3

file 2:
4
5
6

expected:
1
4
2
5
3
6

Have an idea to do that only with the builtins, head, cat, tail and wc ?

thank you so much

CodePudding user response:

if you are okay with using paste command try this.

paste -d "\n" file1.txt file2.txt >> file3.txt

CodePudding user response:

I think you can use following script. It's a simple logic but gets your result.

line_no=`cat file1 |wc -l`
for i in $(seq 1 $line_no)
do
awk "NR==$i" file1 >> file3
awk "NR==$i" file2 >> file3
done

This script assumes both your files have same length. You can change logic to get higher wc for file with higher rows and use it for line_no.

Result:

1
4
2
5
3
6

CodePudding user response:

Here's one way to do it. Not that elegent but should do the trick.

#!/bin/sh

countA=0
while IFS= read -r lineA; do
    countA=$((countA   1)); countB=1
    while [ $countB -le $countA ] && read -r lineB; do
        countB=$((countB   1))
    done < file2
    echo "$lineA"
    echo "$lineB"
done < file1
  • Related