Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if file contains a specific word

In Ruby, how can I check if some file contains some word? I've tried this:

foo = File.open('some-file', 'r').read
foo.index(/^word$/)

But this won't work.

like image 883
Fábio Perez Avatar asked Jan 17 '26 23:01

Fábio Perez


2 Answers

File.readlines('some-file').grep(/word/)

Remeber that ^ matches against the beginning of a line, and $ matches against the end of a line. So if you search for ^xyz$ you are really searching for either xyz\n (beginning of file) or \nxyz\n (somewhere in the middle of the file). No other strings will match.

like image 67
Casper Avatar answered Jan 19 '26 18:01

Casper


You are searching for a line, which contains just that word. Maybe a less constrained search helps:

foo.index(/word/)
like image 36
miku Avatar answered Jan 19 '26 20:01

miku



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!