Skip to content

Instantly share code, notes, and snippets.

@NigoroJr
Created June 9, 2015 01:35
Show Gist options
  • Save NigoroJr/644ae8775023be82544d to your computer and use it in GitHub Desktop.
Save NigoroJr/644ae8775023be82544d to your computer and use it in GitHub Desktop.
Simple script that sorts the output from du
#!/usr/bin/env ruby
# A program that sorts the output from the command `du -h'
# Use it like: du -h . | $PROGRAM_NAME [-r|--reverse]
SUFFIX = {
'K' => 1E3,
'M' => 1E6,
'G' => 1E9,
'T' => 1E12,
'P' => 1E15,
'E' => 1E18,
'Z' => 1E21,
'Y' => 1E24
}
def actual_size(str)
# Check the list character
return str.to_f * SUFFIX[str[-1]] if SUFFIX.key?(str[-1])
str.to_f
end
sorted = STDIN.sort do |a, b|
size_a = a.split(' ')[0]
size_b = b.split(' ')[0]
actual_size(size_a) <=> actual_size(size_b)
end
if ARGV.any? { |arg| arg == '-r' || arg == '--reverse' }
puts sorted.reverse
else
puts sorted
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment