4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

csvのセル内に潜む改行問題

Last updated at Posted at 2016-09-27

csvのセル内に改行があるとExcelで開けないという闇がある.
ってかそもそも扱いづらくなる.

正規表現使ってテキスト処理?

めんどいよね

Rubyでサクッとスクリプト書いて加工しよう!

class CSVつかえばよか

require 'csv'

FILEPATH = ARGV[0]

exit 0 if FILEPATH.nil?

# 一回全部読む
arr = CSV.read(FILEPATH)

# 改行をホワイトスペースに変換
arr.each do |a|
	# /\R/はかなり力強い解法 /(\r\n|\r)/がもっと正確
   a.each { |r| r.gsub!(/\R/, " ") unless r.nil? }
end

# 書き換えするお
CSV.open(FILEPATH, "w") do |csv|
   i = 1
   length = arr.length
   arr.each do |a|
      csv << a
      puts "#{i}/#{length}"
      i += 1
   end
end

これでなんとかなる.

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?