What's the best way to search for a string in a file?

前端 未结 5 2099
悲&欢浪女
悲&欢浪女 2020-12-13 09:07

The title speaks for itself really. I only want to know if it exists, not where it is. Is there a one liner to achieve this?

5条回答
  •  长情又很酷
    2020-12-13 09:29

    This reads the file only to the first appearance of 'string' and processes it line by line - not reading the whole file at once.

    def file_contains_regexp?(filename,regexp)
      File.foreach(filename) do |line|
        return true if line =~ regexp
      end
      return false
    end
    

提交回复
热议问题