File Editor makes it easy to edit a file in place. Just send it a file name and a short block with some instructions, and it will perform string substitution as indicated in the block

===Using File Editor

Your program block can use File Editor in two modes, with or without an explicit receiver:

FileEditor.edit('test.txt') do |editor|
editor.regex = /java/i
editor.substitution_string = 'ruby'
editor.run
end

OR

FileEditor.edit('test.txt') do
@regex = /java/i
@substitution_string = 'ruby'
run
end

The first version does not use instance_eval internally and is therefore able to use variables in the program's local scope. The second version does use instance_eval internally.

Here are some examples, alternating between approaches:

====Standard substitution. File editor will do a line-by-line gsub on the given file

FileEditor.edit('test.txt') do |editor|
editor.regex = /java/i
editor.substitution_string = 'ruby'
editor.run
end

====Setting global to false triggers the use of sub instead of gsub (in effect replacing only the first match on each line)

FileEditor.edit('test.txt') do
@regex = /java/i
@substitution_string = 'ruby'
@global = false
run
end

====Setting keep_backup = true ensures that you'll have a backup of your original file

FileEditor.edit('test.txt') do |editor|
editor.regex = /java/i
editor.substitution_string = 'ruby'
editor.keep_backup = true
editor.run
end

====If you pass in a multiline regex, FileEditor will detect it, read the entire file into a string, and match across new lines

FileEditor.edit('test.txt') do
@regex = /ja.*?va/mi
@substitution_string = 'ruby'
run
end