Skip to content

Instantly share code, notes, and snippets.

@rkumar
Created December 8, 2012 11:31
Show Gist options
  • Save rkumar/4239915 to your computer and use it in GitHub Desktop.
Save rkumar/4239915 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby -w
=begin
* Name : lastpara.rb
* Description : splits a file into paras based on a blank line and prints last one
* Author : rkumar
* Date : 2012-12-08 - 12:54
* Last update : 2012-12-08 17:00
* License :
Same as Ruby's License (http://www.ruby-lang.org/LICENSE.txt)
=end
def usage
e=File.basename($0)
text=<<END
Usage #{e} [-c num] [-r] [-d delim] [--help] file
Prints last (or given) para of given file. Useful for printing
random para from file containing tips/quotes/sigs/notes/log.
Arguments:
-c <0- > which para to print (default is last, index starts at 0)
-d 'delim' delimiter to use for splitting (blank line between paras)
-r print random para
-h --help prints this help
Example:
#{e} quips.txt # print last tip
#{e} -c 1 tips.txt # print first tip
#{e} -r tips.txt # print random tip
#{e} -d '%%%' -r tips.txt # print random tip using %% as delimiter
END
print text
end
num=nil
random= false
delim="\n\n"
# this is a rough approximation of the similar loop I use in shell script
# to avoid optparse and keep it simple. its minimal, and doesn't take combinations like -ltrh
# Loop through as long as there's a '-'
while (ARGV[0][0]=='-')
arg = ARGV.shift
case arg
when '-r'
random=true
when '-c','-n'
# pop off number of para to print
num=ARGV.shift.to_i
when '-d','--delimiter'
# pop off number of para to print
delim=ARGV.shift
when '-h', '--help'
usage
exit
else
print "Wrong argument #{arg} "
usage
exit(1)
end
end
#print "last : #{last} , rec= #{recursive} "
filename = ARGV[0] || exit(-1);
text = File::read(filename)
paras = text.split(delim)
count = paras.size
num ||= count-1
num = rand(count) if random
#rr = rand(count)
puts paras[num]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment