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

前端 未结 5 2080
悲&欢浪女
悲&欢浪女 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:16
    File.open(filename).grep(/string/)
    

    This loads the whole file into memory (slurps the file). You should avoid file slurping when dealing with large files. That means loading one line at a time, instead of the whole file.

    File.foreach(filename).grep(/string/)
    

    It's good practice to clean up after yourself rather than letting the garbage collector handle it at some point. This is more important if your program is long-lived and not just some quick script. Using a code block ensures that the File object is closed when the block terminates.

    File.foreach(filename) do |file|
      file.grep(/string/)
    end
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-13 09:31

    grep for foo OR bar OR baz, stolen from ruby1line.txt.

    $  ruby -pe 'next unless $_ =~ /(foo|bar|baz)/' < file.txt
    
    0 讨论(0)
  • 2020-12-13 09:33

    If your OS has a grep package, you could use a system call:

    system("grep meow cat_sounds.txt")
    

    This will return true if grep returns anything, false if it does not.

    If you find yourself on a system with grep, you may find this is the "best" way because Ruby can be slow when it comes to file operations.

    0 讨论(0)
  • 2020-12-13 09:33

    Well it seems eed3si9n has the one liner down, here's the longer solution:

    f = File.new("file.txt")
    text = f.read
    if text =~ /string/ then
    #relevant code
    end
    
    0 讨论(0)
提交回复
热议问题