Sha256: 30b3ce47dcfb7f0186ede5071c9c7c22acfe1bf8f3688062ef6d90bcd77b589a

Contents?: true

Size: 947 Bytes

Versions: 4

Compression:

Stored size: 947 Bytes

Contents

# extract subset of columns from CSV
require "csv"

class Masticate::Gsubber < Masticate::Base
  def gsub(opts)
    standard_options(opts)

    field = opts[:field] or raise "missing field to gsub"
    from = Regexp.new(opts[:from]) or raise "Invalid regex '#{opts[:from]}' for conversion"
    to = opts[:to] or raise "missing 'to' string for gsub"

    @output_count = 0
    headers = nil
    with_input do |input|
      while line = get
        row = CSV.parse_line(line, csv_options)
        if !headers
          headers = row
          index = headers.index(field) or raise "Unable to find column '#{field}' in headers"
          emit(line)
        else
          oldval = row[index]
          newval = oldval.gsub(from, to)
          row[index] = newval
          emit(row.to_csv)
        end
      end
    end
    @output.close if opts[:output]

    {
      :input_count => input_count,
      :output_count => @output_count
    }
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
masticate-0.1.5 lib/masticate/gsubber.rb
masticate-0.1.4 lib/masticate/gsubber.rb
masticate-0.1.3 lib/masticate/gsubber.rb
masticate-0.1.1 lib/masticate/gsubber.rb