Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if file contains string

So I found this question on here, but I'm having an issue with the output and how to handle it with an if statement. This is what I have, but it's always saying that it's true even if the word monitor does not exist in the file

if File.readlines("testfile.txt").grep(/monitor/)   do something end 

Should it be something like == "nil"? I'm quite new to ruby and not sure of what the outputs would be.

like image 972
Danny Avatar asked Dec 06 '11 23:12

Danny


People also ask

How do you check if a file contains a specific string?

Just run the command directly. Add -q option when you don't need the string displayed when it was found. The grep command returns 0 or 1 in the exit code depending on the result of search.

How do I search for a string in a file in Linux?

If you have a file opened in nano and need to find a particular string, there's no need to exit the file and use grep on it. Just press Ctrl + W on your keyboard, type the search string, and hit Enter .


2 Answers

I would use:

if File.readlines("testfile.txt").grep(/monitor/).any? 

or

if File.readlines("testfile.txt").any?{ |l| l['monitor'] } 

Using readlines has scalability issues though as it reads the entire file into an array. Instead, using foreach will accomplish the same thing without the scalability problem:

if File.foreach("testfile.txt").grep(/monitor/).any? 

or

if File.foreach("testfile.txt").any?{ |l| l['monitor'] } 

See "Why is "slurping" a file not a good practice?" for more information about the scalability issues.

like image 164
the Tin Man Avatar answered Sep 18 '22 18:09

the Tin Man


Enumerable#grep does not return a boolean; it returns an array (how would you have access to the matches without passing a block otherwise?).

If no matches are found it returns an empty array, and [] evaluates to true. You'll need to check the size of the array in the if statement, i.e.:

if File.readlines("testfile.txt").grep(/monitor/).size > 0   # do something end 

The documentation should be your first resource for questions like this.

like image 25
Ed S. Avatar answered Sep 18 '22 18:09

Ed S.