-
-
Save vderyagin/1297560 to your computer and use it in GitHub Desktop.
rcat: cat(1) partial implementation in ruby (passes https://gist.github.com/1293709)
This file contains 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 | |
require 'optparse' | |
options = {} | |
OptionParser.new do |opts| | |
opts.on('-n') { options[:number_all_lines] = true } | |
opts.on('-b') { options[:number_nonblank_lines] = true } | |
opts.on('-s') { options[:squeeze_blank_lines] = true } | |
begin | |
opts.parse! | |
rescue OptionParser::ParseError => e | |
STDERR.puts "rcat: #{e.message}", "usage: rcat [-bns] [file ...]" | |
exit 1 | |
end | |
end | |
def number_lines(text) | |
index = 0 | |
text.each_line.map do |line| | |
"#{(index += 1).to_s.rjust(6)}\t#{line}" | |
end.join | |
end | |
def number_nonblank_lines(text) | |
index = 0 | |
text.each_line.map do |line| | |
if line == "\n" | |
line | |
else | |
"#{(index += 1).to_s.rjust(6)}\t#{line}" | |
end | |
end.join | |
end | |
def squeeze_blank_lines(text) | |
text.each_line.with_object([]) do |line, ary| | |
ary << line unless [line, ary.last].all? { |i| i == "\n" } | |
end.join | |
end | |
begin | |
output = ARGF.read | |
rescue Errno::ENOENT => e | |
STDERR.puts "rcat: #{e.message}" | |
exit 1 | |
end | |
options[:number_all_lines] = false if options[:number_nonblank_lines] | |
output = squeeze_blank_lines output if options[:squeeze_blank_lines] | |
output = number_nonblank_lines output if options[:number_nonblank_lines] | |
output = number_lines output if options[:number_all_lines] | |
print output |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment