Skip to main content

Merge every second line from two files [Resolved]

File1:

A
B
C 
D

File2:

E
F
G
H

How would I get Output:

A
BF
C
DH

Question Credit: tw2000
Question Reference
Asked May 24, 2019
Posted Under: Unix Linux
7 views
6 Answers

Use

awk 'NR==FNR {a[NR]=$0;next} FNR%2==0 { a[FNR]=a[FNR]$0}  END{for ( i in a) print a[i]}' file1 file2

E.g.

#!/bin/bash
echo "a
B
C
D" > file1
echo 'aa
Gd
Er
Yu
Ee
Tt' > file2
awk 'NR==FNR {a[NR]=$0;next} FNR%2==0 { a[FNR]=a[FNR]$0}  END{for ( i in a) print a[i]}' file1 file2

You will get output

a
BGd
C
DYu
Tt

credit: Prvt_Yadv
Answered May 24, 2019

using GNU sed, we may do it as follows:

sed -e 'R file2' file1 | sed -Ee 'N;N;N;s/\n.*(\n.*)\n/\1/'

wherein we emulate the paste via sed and then string the 4 lines together and manipulate in such a manner so as to delete the 2nd and remove the newline between the 3rd and 4th. Repeat this process for the next 4-line slot.


credit: Rakesh Sharma
Answered May 24, 2019

With perl also it is possible to interleave the lines from two files in the desired manner. File 2 is on std in and file 1 is an argument to perl. The line from file2 is added alternately, then the newline is removed.

$ perl -pe '($_ .= ($,,$,.<STDIN>)[$|--]) =~ s/\n(?!\z)//' File1 < File2

credit: Rakesh Sharma
Answered May 24, 2019

Assuming input is on files z7 z8:

paste -d'\0' <(cat z7) <(sed '1~2s/^.*$//' z8)

produces:

A
BF
C
DH

This first deletes all characters on odd lines, leaving the newline. The paste then concatenates the files using a NULL character (thanks to thread paste files without delimiter for the NULL tip).

This was on a system like:

OS, ker|rel, machine: Linux, 3.16.0-7-amd64, x86_64
Distribution        : Debian 8.11 (jessie) 
bash GNU bash 4.3.30
sed (GNU sed) 4.2.2
paste (GNU coreutils) 8.23

Best wishes ... cheers, drl


credit: drl
Answered May 24, 2019
Your Answer
D:\Adnan\Candoerz\CandoProject\vQA