I agree with what other monks have said, i.e. that it is probably not a very good idea to make things more complicated by trying to make them as compact as possible. However, for the sake of the exercise, this is possible one-liner (well, really a two-liner) to do what you want:
perl -F: -nale ' push @d, [@F]; END { print join "\n", map { join ":"
+, @$_}
grep { $c = $$_[1] eq $prec? $c+1:1; $prec = $$_[1]; $c>4? 0: 1} sort
+ {$a->[1] cmp $b->[1] || $b->[0] <=> $a->[0]} @d;};' file.txt
Note that it is also sorting the input by country in the event that the input is not grouped by country. The following is an example execution, piping your reshuffled input data (not grouped by country) into the Perl script:
$ echo '20470:ZM:Samfya:Africa
> 61739:ZW:Chinhoyi:Africa
> 20149:ZM:Sesheke:Africa
> 26459:ZW:Beitbridge:Africa
> 37423:ZW:Bindura:Africa
> 18638:ZM:Siavonga:Africa
> 699385:ZW:Bulawayo:Africa
> 47294:ZW:Chegutu:Africa
> 18860:ZW:Chipinge:Africa
> 28205:ZW:Chiredzi:Africa
> ' | perl -F: -nale ' push @d, [@F];
> END { print join "\n", map { join ":", @$_}
> grep { $c = $$_[1] eq $prec? $c+1:1; $prec = $$_[1]; $c>4? 0: 1}
> sort {$a->[1] cmp $b->[1] || $b->[0] <=> $a->[0]} @d;}'
20470:ZM:Samfya:Africa
20149:ZM:Sesheke:Africa
18638:ZM:Siavonga:Africa
699385:ZW:Bulawayo:Africa
61739:ZW:Chinhoyi:Africa
47294:ZW:Chegutu:Africa
37423:ZW:Bindura:Africa
Edit 15:33 UTC: I posted my final result above only a few hours after I started to look for a solution because I had to interrupt my work on it for family obligations. I had not seen your solution using
splice, it is better than my
grep solution. Overall, I spent probably about 45 minutes to get it (hopefully) right, writing a solution with regular
while or
for loops would have probably taken less than a third of that time.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.