I am new to Ruby and trying to do a find and replace on a text file
based on a regular expression. When I step through the code line by
line, it appears that the appropriate line in the file is changed, but
when I exit the function, the file hasn't been modified. Are in-place
edits of files allowed? can you see what it wrong here?
Here is the body of the function:
def ReplaceGuid(guid)
r = nil
sconfProj = File.open("myfile.vcproj", "r+").each do |line|
m = @guidExp.match(line)
if !m.nil?
str = m[1]
r = %r{#{str}}
line.gsub!(r, guid)
break
end
end
end
OK, I see now it's not trivial to read and write from a file at the
same time, and instead I should probably just drop to the command line
and call
`ruby -pe 'gsub(/foo/, "bar")' < myfile.vcproj`
When i do this, the text of the file spits out to stdio, and it
appears the substitution has been made, but when I open the file in a
text editor, it hasn't been changed.
Am I missing something?
I already checked file permissions and everything looks fine
Thanks,
Jen
`
···
On Mar 24, 2:33 pm, JenC <jcarl...@gmail.com> wrote:
I am new to Ruby and trying to do a find and replace on a text file
based on a regular expression. When I step through the code line by
line, it appears that the appropriate line in the file is changed, but
when I exit the function, the file hasn't been modified. Are in-place
edits of files allowed? can you see what it wrong here?
Here is the body of the function:
def ReplaceGuid(guid)
r = nil
sconfProj = File.open("myfile.vcproj", "r+").each do |line|
m = @guidExp.match(line)
if !m.nil?
str = m[1]
r = %r{#{str}}
line.gsub!(r, guid)
break
end
end
end
OK, I see now it's not trivial to read and write from a file at the
same time, and instead I should probably just drop to the command line
and call
`ruby -pe 'gsub(/foo/, "bar")' < myfile.vcproj`
When i do this, the text of the file spits out to stdio, and it
appears the substitution has been made, but when I open the file in a
text editor, it hasn't been changed.
Am I missing something?
I already checked file permissions and everything looks fine
Or, if you want to keep a backup of the original (and you probably do,
until you know this works the way you expect), you can add an extension
of your choice to the -i flag:
ruby -p -i.bak e 'gsub(/foo/,"bar")' myfile.vcproj
I've actually never used this on Windows, you'll have to try it and see.