开发者

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

开发者 https://www.devze.com 2023-02-08 16:24 出处:网络
How to delete particular line from a textfile in Ruby on Rails? Example : 1: CLEAR,\"Clear\" 2: APPROACH_DIVERGING,\"Approa开发者_开发百科ch Diverging\"

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
0

精彩评论

暂无评论...
验证码 换一张
取 消