如何从Ruby on Rails中的文本文件中删除特定行?
示例:
1: CLEAR , "Clear"
2: APPROACH_DIVERGING , "Approach Diverging"
3: ADVANCE_APPROACH , "Advance Approach"
4: APPROACH_RESTRICTED , "Approach Restricted""
5: APPROACH2 , "Approach"
从上面的例子我想删除第3行。
3: ADVANCE_APPROACH , "Advance Approach"
最后,它会显示如下:
CLEAR , "Clear"
APPROACH_DIVERGING , "Approach Diverging"
APPROACH_RESTRICTED , "Approach Restricted""
APPROACH2 , "Approach"
答案 0 :(得分:4)
您可以将所有行读入数组,然后将它们写回文件,同时省略您不想要的行。 (此代码仅搜索您提到的特定行,但您可以构建正则表达式以与line
进行比较)。
lines = File.readlines(filename)
File.open(filename, "w") do |f|
lines.each { |line| f.puts(line) unless line == "ADVANCE_APPROACH , \"Advance Approach\"") }
end