Last active
December 14, 2015 13:49
-
-
Save chenzx/5096622 to your computer and use it in GitHub Desktop.
Sort lines by field, using index and "number"/"string" compare.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
if ARGV[0] is nil, should i use stdin? this can assit Pipe cmd_a ... | cmd_b ... | ... syntax under Linux