【问题标题】:Remove a string from a Ruby file when it matches a regex匹配正则表达式时从 Ruby 文件中删除字符串
【发布时间】:2014-03-12 12:33:24
【问题描述】:

我正在用 Ruby 编写一个从 Ruby 文件中删除 cmets 的小脚本:

#!/usr/bin/ruby

def uncomment(file)
  File.readlines(file).each do |line|
    if line =~ /(^\s*#|^\t*#)(?!\!).*/
      puts line + " ==> this is a comment"

      #todo: remove line from the file

    end
  end
end


puts "Fetching all files in current directory and uncommenting them"
# fetching all  files
files = Dir.glob("**/**.rb")
# parsing each file
files.each do |file|


  #fetching each line of the current file
  uncomment file

end

我被困在如何删除与#todo 部分中的正则表达式匹配的这些行,如果有人可以提供帮助,那就太好了!

【问题讨论】:

  • 是将结果写入新文件还是修改正在迭代的文件?
  • 是修改当前文件。
  • line.gsub!() 我猜应该也可以。
  • 嗯,正则表达式还匹配在同一行中有代码和注释的行。当您删除这些行时,您的代码可能会无效。

标签: ruby regex file


【解决方案1】:

改变:

def uncomment(file)
  File.readlines(file).each do |line|
    if line =~ /#(?!\!).+/
      puts line + " ==> this is a comment"

      #todo: remove line from the file

    end
  end
end

到:

def uncomment(file)
  accepted_content = File.readlines(file).reject { |line| line =~ /#(?!\!).+/ }
  File.open(file, "w") { |f| accepted_content.each { |line| f.puts line } }
end

您会将接受的行读入一个数组(accepted_content),然后将该数组写回到文件中

【讨论】:

    【解决方案2】:

    我会通过创建一个临时文件来做到这一点:

    open('tmp', 'w') do |tmp| 
      File.open(file).each do |line| 
        tmp << line unless line =~ /#(?!\!).+/ 
      end
    end
    File.rename('tmp', file)
    

    【讨论】:

    • 如果你使用File.open(file).each do |line|逐行读取原始文件而不是使用readlines在内存中读取它并遍历结果数组,这种方法会更有意义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    • 2011-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多