learner
learner

Reputation: 160

combine two files line after line using cat

I have two files: F1, F2 as

F1

f1row1  
f1row2  
..

F2

f2row1  
f2row2  
..

using

cat F1 F2 > F3

gives

f1row1  
f1row2  
..  
<end of file1>
f2row1  
f2row2  
..  
<end of file2>

I would like to create a third file as:

F3

f1row1  
f2row1  
f1row2  
f2row2  
..  

Any suggestions to do this using cat command? I searched for similar questions but didn't find one.

Much thanks.

Upvotes: 2

Views: 237

Answers (2)

iruvar
iruvar

Reputation: 23364

If your input files contain the same number of records

paste -d '\n' F1 F2

Upvotes: 5

konsolebox
konsolebox

Reputation: 75478

Here's a script for Bash. It could work with multiple files (within max opened files limit) not just 2 and could work with variable length of lines.

#!/bin/bash

I=3
for F; do
    eval "exec $I< \"\$F\""
    (( ++I ))
done

for (( ;; )); do
    LINES=()
    for (( J = 3; J < I; ++J )); do
        IFS= read -ru "$J" && LINES+=("$REPLY")
    done
    [[ ${#LINES[@]} -eq 0 ]] && break
    printf '%s\n' "${LINES[@]}"
done

Usage:

bash script.sh file1 file2 ...

Test:

bash script.sh <(seq 1 2) <(seq 1 3) <(seq 1 4)

Output:

1
1
1
2
2
2
3
3
4

And so I'm tempted to compare results with paste:

paste -d '\n' <(seq 1 2) <(seq 1 3)

Output:

1
1
2
2

3

Upvotes: 2

Related Questions