Skip to content

Instantly share code, notes, and snippets.

@zckkte
Created July 7, 2018 03:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zckkte/36c5b2d5f522c896693a3429055b5e34 to your computer and use it in GitHub Desktop.
Save zckkte/36c5b2d5f522c896693a3429055b5e34 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# bam - a simple directory search utility
# author: Zack A. Kite
require 'optparse'
require 'ostruct'
require 'pp'
HIDDEN_DIRS = ['.', '..']
VERSION = 'v1.00'
def parse(args)
options = OpenStruct.new
options.regex = nil
options.directory = Dir.pwd
opt_parse = OptionParser.new do |opts|
#add to banner
opts.banner = "usage: bam [REGEX] [DIR]"
opts.on('-r [REGEX]', '--regex [REGEX]', String,
'regular expression pattern') do |regex_s|
options.regex = Regexp.new regex_s
end
opts.on('-d [DIR]', '--dir [DIR]', String,
'find entries in this directory') do |dir|
options.directory = dir #mandatory path argument
end
opts.on('-h', '--help', nil) do
puts opts
exit
end
opts.on('-v', '--version', nil) do
puts "bam #{VERSION}"
exit
end
end
opt_parse.parse!(args)
return options
end
def main
options = parse(ARGV)
dir_n = options.directory
regex = options.regex
unless Dir.exists? dir_n
puts "bam :- No such file or directory - #{dir_n}"
exit(1)
end
file_list = find regex, File.expand_path(dir_n)
file_list.each do |file|
puts "#{file}"
end
end
def find(regex, dir)
merge_files = []; all_files = []
all_files << dir
dir_entries = Dir.entries(dir) - HIDDEN_DIRS
dir_entries.each do |link|
link_p = File.join(dir, link)
if File.directory? link_p
merge_files = find(regex, link_p)
else
merge_files << link_p
end
merge_files.each do |file|
unless all_files.include? file
all_files << file if file =~ regex
end
end
end
return all_files
end
main if __FILE__ == $0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment