LoginSignup
0
0

More than 5 years have passed since last update.

Count Files By Extension

Posted at

拡張子別にファイル数をカウントします。

file_count.rb
#! /usr/bin/env ruby
require 'pathname'

@directories = 0
@files = {}

def file_count(pathname)
  pathname.each_child  do |child|
    if child.directory?
      @directories += 1
      file_count child
    else
      add_file_by_extenstion child
    end
  end
end

def add_file_by_extenstion(pathname)
  if @files[pathname.extname].nil?
    @files[pathname.extname] = 1
  else
    @files[pathname.extname] += 1
  end
end

if ARGV[0]&.start_with? '-'
  puts <<-EOT
usage: file_count {directory}
  EOT

  exit
end

unless ARGV[0].nil?
  file_count Pathname.new(ARGV[0])
else
  file_count Pathname.new('.')
end

puts "#{@directories}\tdirectories"
@files.each do |extension, count|
  if extension == ""
    puts "#{count}\tno extension"
  else
    puts "#{count}\t#{extension}"
  end
end

実行例

sample.jpg

0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0