Ruby replace weirdly encoded string without gsub

Having a bunch of files with weird encoding you need to replace something in ?
Pru to the rescue!
(because replacing with ruby-regex or sed leads to encoding exceptions)


find test -name "*" | pru 'return unless File.file?(self); c = File.read(self); s = "SEARCH"; r = "REPLACE"; while x = c.index(s) do; c.slice!(x,s.size); c.insert(x, r); end; File.write(self, c)'

Normal ruby:

String.class_eval do
  def string_sub(s,r)
    while x = index(s) do
      slice!(x,s.size)
      insert(x, r)
    end
    self
  end
end

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s