Class: Nito::Sed

Inherits:
Object
  • Object
show all
Defined in:
lib/nito/sed.rb

Instance Method Summary collapse

Constructor Details

#initialize(file, regex, change) ⇒ Sed

Returns a new instance of Sed.



5
6
7
8
9
10
# File 'lib/nito/sed.rb', line 5

def initialize(file, regex, change)
  @file = file
  @regex = regex
  @change = change
  apply
end

Instance Method Details

#applyObject



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/nito/sed.rb', line 12

def apply
  raise ArgumentError "No file #{@file} exist" if ! File.exist? @file
  tmp = Tempfile.new('sed')
  File.open(@file).each { |l|
    if l.match(@regex)
      File.write(tmp, "#{@change}\n", mode: 'a')
    else
      File.write(tmp, l, mode: 'a')
    end
  }
  Nito::Cp.new(tmp.path, @file)
end