How to delete particular line from a textfile in Ruby on Rails?
How to delete particular line from a textfile in Ruby on Rails?
Example :
1: CLEAR , "Clear"
2: APPROACH_DIVERGING , "Approa开发者_开发百科ch Diverging"
3: ADVANCE_APPROACH , "Advance Approach"
4: APPROACH_RESTRICTED , "Approach Restricted""
5: APPROACH2 , "Approach"
From above example I want to the delete 3rd line.
3: ADVANCE_APPROACH , "Advance Approach"
Finally, it will display like this:
CLEAR , "Clear"
APPROACH_DIVERGING , "Approach Diverging"
APPROACH_RESTRICTED , "Approach Restricted""
APPROACH2 , "Approach"
You could read all the lines into an array, then write them back to the file while omitting the lines you don't want. (This code only searches for the specific line you mentioned, but you could build a regular expression to compare to line
instead).
lines = File.readlines(filename)
File.open(filename, "w") do |f|
lines.each { |line| f.puts(line) unless line == "ADVANCE_APPROACH , \"Advance Approach\"") }
end
精彩评论