Last active
April 4, 2020 08:38
-
-
Save DivineDominion/0e72082a79359866a15558cba5c67e9a to your computer and use it in GitHub Desktop.
Find a random plain text file in a directory
This file contains hidden or 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
#!/usr/bin/env ruby | |
# Usage: random_file.rb [options] | |
# -d, --dir [VALUE] Path to the note archive. Default: the current working directory. | |
# -c, --count [VALUE] Amount of unique random notes to fetch | |
# -h, --help Prints this help | |
require "optparse" | |
CURRENT_PATH = Dir.pwd | |
options = { | |
directory: CURRENT_PATH, | |
amount: 1 | |
} | |
parser = OptionParser.new do |o| | |
o.banner = "Usage: #{__FILE__} [options]" | |
o.on("-d", "--dir [VALUE]", "Path to the note archive. Default: the current working directory (#{CURRENT_PATH})") do |val| | |
path = File.expand_path(val.to_s) | |
if File.exist?(path) | |
options[:directory] = path | |
else | |
abort %Q{Directory at path #{path} does not exist} | |
end | |
end | |
o.on("-c", "--count [VALUE]", "Amount of unique random notes to fetch") do |val| | |
options[:amount] = val.to_i | |
end | |
o.on_tail("-h", "--help", "Prints this help") do | |
STDOUT.puts o | |
exit | |
end | |
end | |
parser.parse! | |
# puts options | |
EXTENSIONS = ["markdown", "md", "mmd", "txt", "text"] | |
def extension(path) | |
filename = File.basename(path) | |
filename_without_ext = File.basename(path, ".*") | |
# Take the remainder, without the dot, after the filename | |
return filename[filename_without_ext.length + 1 .. -1] | |
end | |
results = [] | |
Dir.chdir(options[:directory]) do | |
all_files = Dir.glob("*").select { |f| EXTENSIONS.include?(extension(f))} | |
options[:amount].times do | |
remainder = all_files - results | |
next_file = remainder.sample | |
break if next_file.nil? | |
results << next_file | |
end | |
end | |
STDOUT.puts results |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example
Command
Example output:
Sorted Example
Command, piping the output to
sort
:Example output: