#!usr/bin/perl use strict; use warnings; use 5.010; my %data; # Parse data while () { chomp; my ($key, @chunks) = /(\w+ (?:\([^)]*\))?) (?: \s+ |$)/gx; next if !@chunks; foreach my $chunk (@chunks) { my ($prefix, $num, $tail) = $chunk =~ /^([a-z0-9]+)_(\d+)(.*)/i; $data{$key}{$prefix}{$num} = $tail; } } # Create lists of values for my $key (keys %data) { for my $prefix (keys %{$data{$key}}) { my @items = map {"${prefix}_$_$data{$key}{$prefix}{$_}"} sort {$a <=> $b} keys %{$data{$key}{$prefix}}; $data{$key}{$prefix} = \@items; } } # Generate output for my $key (sort keys %data) { my @prefixes = sort keys %{$data{$key}}; my @lines; my @colMax; while (1) { my @items = ($key, map {shift @{$data{$key}{$_}}} @prefixes); last if 1 >= grep {defined} @items; $_ //= ' -' for @items; push @lines, \@items; } for my $line (@lines) { for my $colIndex (0 .. $#$line) { my $itemWidth = length $line->[$colIndex]; $colMax[$colIndex] = $itemWidth if !$colMax[$colIndex] || $itemWidth > $colMax[$colIndex]; } } for my $line (@lines) { $line->[$_] = sprintf '%-*s', $colMax[$_], $line->[$_] for 0 .. $#$line; } print "@$_\n" for @lines; } __DATA__ ClusterX a_123(something) b_675(some_other_thing) b_234(something new) c_897(some different thing) ClusterY b_6998(some_other_thing, thats new) c_877797(something different inside here) c_111(some other different thing) ClusterZ a_1234(something interesting) a_123467(something - else thats is - interesting) 3850-1-2_12243(a new one) 3850-1-2_1789(another new one) #### ClusterX a_123(something) b_234(something new) c_897(some different thing) ClusterX - b_675(some_other_thing) - ClusterY b_6998(some_other_thing, thats new) c_111(some other different thing) ClusterY - c_877797(something different inside here) ClusterZ 2_1789(another new one) a_1234(something interesting) ClusterZ 2_12243(a new one) a_123467(something - else thats is - interesting)