How to sort a file by its columns

Jun 04
2009
# sort by user id
ruby -a -F: -ne 'puts $F.values_at(2, 0).join("\t")' '/etc/passwd' | sort -g
 
# sort by user home directory
ruby -a -F: -ne 'puts $F.values_at(5, 0).join("\t")' '/etc/passwd' | sort -g
 
# sort by username
ruby -a -F: -ne 'puts $F.values_at(0).join("\t")' '/etc/passwd' | sort -g

Sorting an Array of Hashes with unknown keys

Jul 19
2008
AoH = [{"z"=>26}, {"g"=>7}, {"r"=>18}, {"a"=>1}, {"v"=>22}]
 
# sort by key
AoH.map{|e| e.to_a.flatten}.sort{|x,y| x[0] < => y[0]}
# sort by value
AoH.map{|e| e.to_a.flatten}.sort{|x,y| x[1] < => y[1]}

Sort By Part Of Filename

Jan 12
2008

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

Calendar

February 2012
M T W T F S S
« Sep    
 12345
6789101112
13141516171819
20212223242526
272829  

Tags