Newcolour
Newcolour

Reputation: 47

Merge lines matching a regex from another file

I am trying to do the following and I have not yet succeeded. I have two files:

header1
data11
data12
data13
header2
data21
data22
data23
header3
data31
data32
data33
header4
data41
data42
data43
...
headerN
dataN1
dataN2
dataN3

and the other is

header1 num11 num12 num13 num14
header2 num21 num22 num23 num24
header5 num51 num52 num53 num54
header8 num81 num82 num83 num84
...

I need to have as output a file that selects the header from file 2 and prints out in the following format (using the above example)

header1
data11
num11
num13
data12
data13
header2
data21
num21
num23
data22
data23
header5
data51
num51
num53
data52
data53
...

I hope it's clear: I need the header (which should be identified to be common to the two files), the first line of file 1, the second and fourth column of the file 2, the rest of the data of file 1 for that header, and so forth. I have been trying with awk but I have not been able to get what I want from a simple "two files one-liner" :)

EDIT: Sorry for being misleading. I am not requiring a one-liner. I am just saying I have used a few awk and grep one-liners. I'd like something that works only :) Also, the headers are alphanumeric, with no easy pattern. I need recognition of the whole string.

Upvotes: 2

Views: 318

Answers (1)

Brian Swift
Brian Swift

Reputation: 1443

This is the ugly one liner I came up with (developed on a command line):

while read h n1 n2 n3 n4; do echo $h; sed -n -e "/^$h\$/{" -e n -e p -e q -e '}'  file1 ; echo $n1; echo $n3; sed -n -e "/^$h\$/{" -e n -e n -e p -e n -e p -e q -e '}'  file1 ;  done <file2

I'm assuming that for every header in file2 there is a corresponding header in file1

Upvotes: 3

Related Questions