fjord/wc.rb

39 lines
849 B
Ruby
Raw Normal View History

2024-07-02 22:44:35 +09:00
# frozen_string_literal: true
2024-07-01 09:32:50 +09:00
2024-07-02 22:44:35 +09:00
require 'optparse'
2024-07-01 09:32:50 +09:00
2024-07-02 22:44:35 +09:00
lines = 0
words = 0
bytes = 0
options = {}
OptionParser.new do |opts|
2024-07-03 22:17:39 +09:00
opts.on('-l') { options[:lines] = true }
opts.on('-w') { options[:words] = true }
opts.on('-c') { options[:bytes] = true }
2024-07-02 22:44:35 +09:00
end.parse!
2024-07-01 09:32:50 +09:00
2024-07-03 22:17:39 +09:00
input = if !ARGV.empty?
File.read(ARGV[0])
elsif !$stdin.tty?
$stdin.read
else
puts 'ファイルパスまたはパイプラインからの入力がありません。'
exit
end
2024-07-01 09:32:50 +09:00
2024-07-03 22:17:39 +09:00
input.each_line do |line|
lines += 1
words += line.split.size
bytes += line.bytesize
2024-07-02 22:44:35 +09:00
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]
2024-07-03 22:17:39 +09:00
file_name = ARGV[0]
puts "#{result.join(' ')} #{file_name}"