This commit is contained in:
Rikuoh Tsujitani 2024-07-10 14:55:39 +09:00
parent 40c822d7f1
commit 17fded3633

43
wc.rb
View file

@ -2,9 +2,9 @@
require 'optparse' require 'optparse'
lines = 0 total_lines = 0
words = 0 total_words = 0
bytes = 0 total_bytes = 0
options = {} options = {}
OptionParser.new do |opts| OptionParser.new do |opts|
@ -13,14 +13,15 @@ OptionParser.new do |opts|
opts.on('-c') { options[:bytes] = true } opts.on('-c') { options[:bytes] = true }
end.parse! end.parse!
input = if !ARGV.empty? input_sources = ARGV.empty? ? [ARGF] : ARGV
File.read(ARGV[0])
elsif !$stdin.tty? input_sources.each do |source|
$stdin.read lines = 0
else words = 0
puts 'ファイルパスまたはパイプラインからの入力がありません。' bytes = 0
exit
end begin
input = source == ARGF ? ARGF.read : File.read(source)
input.each_line do |line| input.each_line do |line|
lines += 1 lines += 1
@ -28,11 +29,27 @@ input.each_line do |line|
bytes += line.bytesize bytes += line.bytesize
end end
total_lines += lines
total_words += words
total_bytes += bytes
options = { bytes: true, lines: true, words: true } if options.empty? options = { bytes: true, lines: true, words: true } if options.empty?
result = [] result = []
result << lines if options[:lines] result << lines if options[:lines]
result << words if options[:words] result << words if options[:words]
result << bytes if options[:bytes] result << bytes if options[:bytes]
file_name = ARGV[0] puts "#{result.join(' ')} #{source == ARGF ? '' : source}"
puts "#{result.join(' ')} #{file_name}" rescue Errno::ENOENT
puts "wc: #{source}: そのようなファイルやディレクトリはありません"
end
end
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]
puts "#{total_result.join(' ')} total"
end