How to delete particular line from a textfile in Ruby on Rails?

952 views Asked by At

How to delete particular line from a textfile in Ruby on Rails?

Example :

1: CLEAR                  ,  "Clear"
2: APPROACH_DIVERGING     ,  "Approach 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"
1

There are 1 answers

0
Dylan Markow On

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