Skip to content

Instantly share code, notes, and snippets.

@chenzx
Last active December 14, 2015 13:49
Show Gist options
  • Save chenzx/5096622 to your computer and use it in GitHub Desktop.
Save chenzx/5096622 to your computer and use it in GitHub Desktop.
Sort lines by field, using index and "number"/"string" compare.
all_line_objs = Array.new()
FIELD_SPLITTER = ' ' #change to '\t', ',', ':' as you need;
FIELD_INDEX = 1 #Start from 0;
FIELD_TYPE = "number" #number or string;
File.open(ARGV[0]).each { |line|
fields = line.strip.split(FIELD_SPLITTER)
field = fields[FIELD_INDEX]
line_obj = {field:field, line:line.strip}
all_line_objs.push line_obj
}
all_line_objs.sort {|a, b|
if FIELD_TYPE == "number" then
b[:field].to_f <=> a[:field].to_f #reverse;
else
a[:field] <=> b[:field]
end
}.each {|line_obj|
puts line_obj[:line]
}
@chenzx
Copy link
Author

chenzx commented Mar 6, 2013

if ARGV[0] is nil, should i use stdin? this can assit Pipe cmd_a ... | cmd_b ... | ... syntax under Linux

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment