tags:

views:

514

answers:

4

Hi,

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?

Regards,

Chris

+5  A: 

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

$  ruby -pe 'next unless $_ =~ /(foo|bar|baz)/' < file.txt
eed3si9n
+1  A: 

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
John T
You need to quote your file name.
Ryan Bigg
yeah just noticed while you posted this
John T
one-liner: `whatever(x) if File.read("file.txt") =~ /regex/`
rampion
A: 

Cheatng a little by using a system call:

system("grep meow cat_sounds.txt")

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

I find this is the "best" way because Ruby is slow when it comes to file operations.

Ryan Bigg
he hasnt specified his os yet =\
John T
I think it's best to assume he's sane.
Ryan Bigg
Funily enough it was a rakefile I was creating when I came up with this question, so I can even re-factor this to sh "grep meow cat_sounds.txt" :-)
ChrisInCambo
And it still returns true / false? Cool! http://rake.rubyforge.org/classes/FileUtils.html#M000018 haha! The example is even grepping!
Ryan Bigg
What does sanity have to do with the fact that not all OSes have a "grep" command?
bk1e
I find it insane that people try to run Ruby on Windows, given all the pitfalls.
Ryan Bigg
Ruby works on Windows quite well actually. But then you have the gems....*grimace of pain*. Still, it's my language of choice for system scripts.
SimonV
A: 
open('some.txt').grep(/string/)
AdamK