Replace string in a file : Text file « File Directory « Ruby






Replace string in a file


def stringReplace(searchString, replaceString, fileName)
  aFile = File.open(fileName, "r")
  aString = aFile.read
  aFile.close

  aString.gsub!(searchString, replaceString)

  File.open(fileName, "w") { |file| file << aString }
end

stringReplace(*ARGV)

 








Related examples in the same category

1.
2.Use each method to loop through a text file
3.Read line from a text file
4.Output each line in a file and close it
5.Use code block to insert string to a file
6.Read a text file with File.read
7.Read a text file readlines