wc
This commit is contained in:
parent
40c822d7f1
commit
17fded3633
1 changed files with 39 additions and 22 deletions
61
wc.rb
61
wc.rb
|
@ -2,9 +2,9 @@
|
|||
|
||||
require 'optparse'
|
||||
|
||||
lines = 0
|
||||
words = 0
|
||||
bytes = 0
|
||||
total_lines = 0
|
||||
total_words = 0
|
||||
total_bytes = 0
|
||||
|
||||
options = {}
|
||||
OptionParser.new do |opts|
|
||||
|
@ -13,26 +13,43 @@ OptionParser.new do |opts|
|
|||
opts.on('-c') { options[:bytes] = true }
|
||||
end.parse!
|
||||
|
||||
input = if !ARGV.empty?
|
||||
File.read(ARGV[0])
|
||||
elsif !$stdin.tty?
|
||||
$stdin.read
|
||||
else
|
||||
puts 'ファイルパスまたはパイプラインからの入力がありません。'
|
||||
exit
|
||||
end
|
||||
input_sources = ARGV.empty? ? [ARGF] : ARGV
|
||||
|
||||
input.each_line do |line|
|
||||
lines += 1
|
||||
words += line.split.size
|
||||
bytes += line.bytesize
|
||||
input_sources.each do |source|
|
||||
lines = 0
|
||||
words = 0
|
||||
bytes = 0
|
||||
|
||||
begin
|
||||
input = source == ARGF ? ARGF.read : File.read(source)
|
||||
|
||||
input.each_line do |line|
|
||||
lines += 1
|
||||
words += line.split.size
|
||||
bytes += line.bytesize
|
||||
end
|
||||
|
||||
total_lines += lines
|
||||
total_words += words
|
||||
total_bytes += bytes
|
||||
|
||||
options = { bytes: true, lines: true, words: true } if options.empty?
|
||||
result = []
|
||||
result << lines if options[:lines]
|
||||
result << words if options[:words]
|
||||
result << bytes if options[:bytes]
|
||||
|
||||
puts "#{result.join(' ')} #{source == ARGF ? '' : source}"
|
||||
rescue Errno::ENOENT
|
||||
puts "wc: #{source}: そのようなファイルやディレクトリはありません"
|
||||
end
|
||||
end
|
||||
|
||||
options = { bytes: true, lines: true, words: true } if options.empty?
|
||||
result = []
|
||||
result << lines if options[:lines]
|
||||
result << words if options[:words]
|
||||
result << bytes if options[:bytes]
|
||||
if input_sources.size > 1
|
||||
total_result = []
|
||||
total_result << total_lines if options[:lines]
|
||||
total_result << total_words if options[:words]
|
||||
total_result << total_bytes if options[:bytes]
|
||||
|
||||
file_name = ARGV[0]
|
||||
puts "#{result.join(' ')} #{file_name}"
|
||||
puts "#{total_result.join(' ')} total"
|
||||
end
|
||||
|
|
Loading…
Reference in a new issue