Check if file contains string

后端 未结 4 565
无人及你
无人及你 2021-01-31 15:40

So I found this question on here, but I\'m having an issue with the output and how to handle it with an if statement. This is what I have, but it\'s always saying that it\'s tru

相关标签:
4条回答
  • 2021-01-31 15:41

    if anyone is looking for a solution to display last line of a file where that string occurs just do

    File.readlines('dir/testfile.txt').select{|l| l.match /monitor/}.last 
    

    example

    file:

    monitor 1
    monitor 2
    something else
    

    you'll get

    monitor 2
    
    0 讨论(0)
  • 2021-01-31 15:51

    Enumerable#grep does not return a boolean; it returns an array (how would you have access to the matches without passing a block otherwise?).

    If no matches are found it returns an empty array, and [] evaluates to true. You'll need to check the size of the array in the if statement, i.e.:

    if File.readlines("testfile.txt").grep(/monitor/).size > 0
      # do something
    end
    

    The documentation should be your first resource for questions like this.

    0 讨论(0)
  • 2021-01-31 15:54

    Grep will give you an array of all found 'monitor's. But you don't want an array, you want a boolean: is there any 'monitor' string in this file? This one reads as little of the file as needed:

    if File.open('test.txt').lines.any?{|line| line.include?('monitor')}
      p 'do something'
    end
    

    readlines reads the whole file, lines returns an enumerator which does it line by line.

    0 讨论(0)
  • 2021-01-31 15:57

    I would use:

    if File.readlines("testfile.txt").grep(/monitor/).any?
    

    or

    if File.readlines("testfile.txt").any?{ |l| l['monitor'] }
    

    Using readlines has scalability issues though as it reads the entire file into an array. Instead, using foreach will accomplish the same thing without the scalability problem:

    if File.foreach("testfile.txt").grep(/monitor/).any?
    

    or

    if File.foreach("testfile.txt").any?{ |l| l['monitor'] }
    

    See "Why is "slurping" a file not a good practice?" for more information about the scalability issues.

    0 讨论(0)
提交回复
热议问题