#!/usr/bin/perl # http://perlmonks.org/?node_id=1171182 use strict; use warnings; $_ = join '', ; 1 while s/^(\S+ \S+ ).*\K\n((?:.*\n)*)\1(.*\n)/:$3$2/m; print; __DATA__ A1 abc yellow B1 xyz green A2 cde red A1 abc green A2 cde yellow A1 abc blue