LoginSignup
4
4

More than 5 years have passed since last update.

テキストファイルを特定の行数の複数のファイルに分割する

Posted at
split_file_by_lines.rb
# encoding: utf-8

if ARGV.length != 2 then
  abort "引数の数が正しくありません。\nruby split_file_by_lines.rb source_file lines_limit"
end

source_file, lines_limit = ARGV
source_file_name = File.basename(source_file, '.*')
source_file_ext = File.extname(source_file)

lines = []
File.foreach(source_file) {|line|
  lines << line
}

div = lines.count.div(lines_limit.to_i)
file_count = div + 1

file_no = 1
lines.each_slice(lines_limit.to_i) {|e|
  # ファイル名に付与する連番を作成する
  file_no_suffix = "#{sprintf('%0' + file_count.to_s.length.to_s + 'd', file_no)}"

  # 分割したファイルを出力する
  out_file_name = "#{source_file_name}_#{file_no_suffix}#{source_file_ext}"
  File.open(out_file_name, 'w') {|f|
    f.write e.join
  }
  file_no += 1
}
4
4
0

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
4
4