Sudhi Sudhi - 7 months ago 10
Bash Question

Merge two text files block by block

I have two text files each containing a block of text separated by empty lines. The blocks vary in sizes.

# ::id 10
# ::snt Yes !
...multiple lines of unstructured data from file 1...

# ::id 11
# ::snt said Lion .
...multiple lines of unstructured data from file 1...

# ::id 12
# ::snt Yes yes !
...multiple lines of unstructured data from file 1...

# ::id 13
# ::snt said Tiger .
...multiple lines of unstructured data from file 1...


and similarly another

# ::id 10
# ::snt No !
...multiple lines of unstructured data from file 2...

# ::id 11
# ::snt said Monkey .
...multiple lines of unstructured data from file 2...

# ::id 12
# ::snt No no !
...multiple lines of unstructured data from file 2...

# ::id 13
# ::snt said Donkey .
...multiple lines of unstructured data from file 2...


I want to merge the two blocks, but sort them by their
# ::id
. Also, I need to mainain the order of file1 data blocks before file2 data blocks. So final output should be something like:

# ::id 10
# ::snt Yes !
...multiple lines of unstructured data from file 1...

# ::id 10
# ::snt No !
...multiple lines of unstructured data from file 2...

# ::id 11
# ::snt said Lion .
...multiple lines of unstructured data from file 1...

# ::id 11
# ::snt said Monkey .
...multiple lines of unstructured data from file 2...

# ::id 12
# ::snt Yes yes !
...multiple lines of unstructured data from file 1...

# ::id 12
# ::snt No no !
...multiple lines of unstructured data from file 2...

# ::id 13
# ::snt said Tiger .
...multiple lines of unstructured data from file 1...

# ::id 13
# ::snt said Donkey .
...multiple lines of unstructured data from file 2...


How do I do it? Anything will work
bash
,
sed
,
awk

Answer
$ awk -v RS= -v ORS='\n\n' 'NR==FNR{a[NR]=$0;next} {print a[FNR] ORS $0}' file1 file2
# ::id 10
# ::snt Yes !

# ::id 10
# ::snt No !

# ::id 11
# ::snt said Lion .

# ::id 11
# ::snt said Monkey .

# ::id 12
# ::snt Yes yes !

# ::id 12
# ::snt No no !

# ::id 13
# ::snt said Tiger .

# ::id 13
# ::snt said Donkey .
Comments