Sort By Part Of Filename

Posted by root Sat, 12 Jan 2008 08:57:00 GMT

Assume that we have directory, containing files like:

part_1.txt
part_2.txt
part_100.txt
part_200.txt

In case that we are interested in /(\d+)\.\w+$/ as part of the sorting criteria:

Perl
# short but unefficient
@a = sort {($a =~ /(\d+)\.\w+$/)[0] <=> ($b =~  /(\d+)\.\w+$/)[0]} <*>;

Ruby
regex = Regexp.new(/(\d+)\.\w+$/)

# enum.sort {| a, b | block } => array
Dir["*"].grep(regex).sort do |a, b|
  a.match(regex)[0].to_i <=> b.match(regex)[0].to_i
end

# enum.sort_by {| obj | block } => array
Dir["*"].grep(regex).sort_by do |name|
  name.match(regex)[1].to_i
end

Posted in ,  | Tags  | no comments