Skip to content

Instantly share code, notes, and snippets.

@MtnBiker
Created February 26, 2014 04:20
Show Gist options
  • Save MtnBiker/9223513 to your computer and use it in GitHub Desktop.
Save MtnBiker/9223513 to your computer and use it in GitHub Desktop.
textfile = 'w2e2.textFile.txt'
word_to_change = "word"
new_word = "inserted word"
lineArr = []
newTextContents = ""
File.open(textfile, 'r') do |f1|
while line = f1.gets
lineArr = line.split(" ")
# should be done with RegEx, but since we haven't done that yet
lineArr.each { |x|
i =+ 1
if x == word_to_change
lineArr[i+1] = new_word
end
}
newTextContents << lineArr.join(" ") + "\n"
end
puts "\n#{newTextContents}"
puts "\n\nNeed to write to file, may need to close file above"
File.open('textfilenew', 'w') do |f2|
f2.puts newTextContents
end
end
# Used a new file to write to, so could run this more than once. I believe the effect would be the same. Will test it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment