Is there anyway to check if a value exist in a file without ALWAYS going through entire file ?
Currently I used:
if open('file.txt').grep(/value/).length > 0
puts "match"
else
puts "no match"
end
But it's not efficient as I only want to know whether it exists or not. Really appreciate a solution with grep / others similar one-liner.
Please not开发者_运维问答e the "ALWAYS" before down-vote my question
If you want line-by-line comparison using a one-liner:
matches = open('file.txt') { |f| f.lines.find { |line| line.include?("value") } }
puts matches ? "yes" : "naaw"
By definition, the only way you can tell if an arbitrary expression exists in a file is by going over the file and looking for it. If you're looking for the first instance, then on average you'll be scanning half the file until you find your expression when it's there. If the expression isn't there then you'll have to scan the entire file to figure that out.
You could implement that in a one-liner by scanning the file line-by-line. Use IO.foreach
If you do this often, then you can make the search super efficient by indexing the file first, e.g. by using Lucene. It's a trade-off - you still have to scan the file, but only once since you save it's content in a more search-friendly data structure. However, if you don't access a given file very frequently, it's probably not worth the overhead - implementation, maintenance and extra storage.
Here's a ruby one-liner that will work from the linux command line to perform a grep on a text file, and stop on first found.
ruby -ne '(puts "first found on line #{$.}"; break) if $_ =~ /regex here/' file.txt
-n gets each line in the file and feeds it to the global variable $_
$. is a global variable that stores the current line number
If you want to find all lines matching the regex, then:
ruby -ne 'puts "found on line #{$.}" if $_ =~ /regex here/' file.txt
精彩评论