Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to search for a string in a file?

Tags:

ruby

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?

like image 996
ChrisInCambo Avatar asked Mar 11 '09 05:03

ChrisInCambo


People also ask

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

Grep is a Linux / Unix command-line tool used to search for a string of characters in a specified file. The text search pattern is called a regular expression. When it finds a match, it prints the line with the result. The grep command is handy when searching through large log files.

How do I find all files containing specific text?

Without a doubt, grep is the best command to search a file (or files) for a specific text. By default, it returns all the lines of a file that contain a certain string. This behavior can be changed with the -l option, which instructs grep to only return the file names that contain the specified text.

How do you search for the string my string is the best in files of a directory recursively?

You can use grep command or find command as follows to search all files for a string or words recursively.


1 Answers

File.open(filename).grep(/string/) 

This loads the whole file into memory (slurps the file). You should avoid file slurping when dealing with large files. That means loading one line at a time, instead of the whole file.

File.foreach(filename).grep(/string/) 

It's good practice to clean up after yourself rather than letting the garbage collector handle it at some point. This is more important if your program is long-lived and not just some quick script. Using a code block ensures that the File object is closed when the block terminates.

File.foreach(filename) do |file|   file.grep(/string/) end 
like image 91
AdamK Avatar answered Sep 26 '22 22:09

AdamK