#!/usr/bin/perl # https://perlmonks.org/?node_id=11104187 use strict; use warnings; print map $_->[0], sort { $a->[1] cmp $b->[1] } map [ $_, m{/search/(.*?)\?} ], ; __DATA__ http://myurl.com/search/stringA?SomeMoreStuffA http://myurlA.com/search/stringB?SomeMoreStuffB http://myurlB.com/search/stringC?SomeMoreStuffX http://myurlC.com/search/stringA?SomeMoreStuffXYZ http://myurl.com/search/stringZ?SomeMoreStuffZZZ