Skip to content

Instantly share code, notes, and snippets.

@pasberth
Created August 25, 2011 14:39
Show Gist options
  • Select an option

  • Save pasberth/1170814 to your computer and use it in GitHub Desktop.

Select an option

Save pasberth/1170814 to your computer and use it in GitHub Desktop.
find コマンドみたいなの
# -*- coding: utf-8 -*-
# usage: ruby find.rb ~ --name .* --depth 1
# need to OptParser
require "optparser"
$filename = nil
$rootdir = File.expand_path '.'
$recursive = true
OptParser.add_option('--name') { |filename|
$filename = filename
}
OptParser.add_option('--depth') { |depth|
$recursive = depth.to_i
}
OptParser.main = proc { |rootdir|
$rootdir = File.expand_path rootdir
}
OptParser.parse_options
unless $filename
puts "plz to put --name"
exit
end
unless File.exist? $rootdir
puts "#{$rootdir} is not exist."
end
unless File.directory? $rootdir
puts "#{$rootdir} is not directory."
end
def find rootdir, wantfilename=/.*/, recursive=true, &callback
res = []
Dir.entries(rootdir)[2..-1].each do |entry|
res << entry if entry =~ wantfilename
abspath = "#{rootdir}/#{entry}"
case recursive
when Numeric
if (File.directory? abspath) && (recursive > 0)
callback.call abspath if callback
res += find abspath, wantfilename, recursive-1, &callback
end
else
if (File.directory? abspath) && recursive
callback.call abspath if callback
res += find abspath, wantfilename, recursive, &callback
end
end
end
res
end
find($rootdir, Regexp.new($filename), $recursive) { |filename| puts filename }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment