开发者

Check if file contains a specific word

开发者 https://www.devze.com 2023-03-28 06:31 出处:网络
In Ruby, how can I check if some file contains some word? I\'ve tried this: foo = File.open(\'some-file\', \'r开发者_StackOverflow社区\').read

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

foo = File.open('some-file', 'r开发者_StackOverflow社区').read
foo.index(/^word$/)

But this won't work.


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.


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

foo.index(/word/)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号