Ruby grep, match and return
10,118
Solution 1
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"
Solution 2
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
Comments
-
w00d almost 2 years
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 note the "ALWAYS" before down-vote my question
-
MarkD over 12 yearsAnd how exactly do you plan to check if a file contains a value without going through the entire file?
-
w00d over 12 years@Tempos: for example, if the value is at the beginning of the file, I want it to return immediately after seeing it
-
MarkD over 12 yearsNo matter how you put it, you have to go over the whole file, at least once.
-
w00d over 12 years@Tempos: why ? If in normal implementation, "while (until eof) if (thisline == 'x') then closefile and return" rather than "while( until eof ) do if (thisline =='x') record and next", is it still not clear to you ? If there is no value, yes it will run entire file, but if there is multiple value, it only read the file until the first value found
-
Dave Newton over 12 yearsSo write a method that does it line-by-line (assuming your pattern can't cross line boundaries)--easy enough.
-
MarkD over 12 years@iKid, the algorithm to check will go through the whole file on the scenario that the value doesn't exist. This was what I was trying to say.
-
w00d over 12 years@Tempos: Yes I know, that's why my question is "without always going through entire file" Notice the "ALWAYS"
-
w00d over 12 years@Dave Newton: I'm asking a feature of grep or a one-liner, I can easily write for loop, please check my question
-
Dave Newton over 12 yearsGoing through line-by-line would be a one-liner too, or you could use find. Basically you're asking why "grep", which finds all matches, finds all matches.
-
w00d over 12 yearsCan you write a neat one liner with "Going through line-by-line" ? to replace my "if open('file.txt').grep(/value/).length > 0" ?
-
-
Niklas B. over 12 yearsthe puts seems to break it (as I didn't specify parenthesis around the if).