Home » Questions » Computers [ Ask a new question ]

A better way to search for a string within a file?

A better way to search for a string within a file?

I am trying to find a particular string of text in a file somewhere on my hard drive. The best I have come up with so far is:

Asked by: Guest | Views: 48
Total answers/comments: 3
Guest [Entry]

"find / -type f -exec grep ""string"" {} +

This will perform a case insensitive search which will be slower, but more flexible:

find / -type f -exec grep -i ""string"" {} +

you may get a lot of results so you can pipe it to less, then use f and b to navigate forward and backward page by page through the output:

find / -type f -exec grep -i ""string"" {} + | less

If you know you are looking for *.txt files, you can refine it even more:

find / -type f -name ""*.txt"" -exec grep -i ""string"" {} + | less"
Guest [Entry]

"Why use 'cat' at all in this case? I always find it odd how people use 'cat' for no reason at all. Just do:

find -type f / | xargs grep ""string to find""

Of course searching every single file on your entire disk will be quite slow. You're probably better off using some kind of indexing program if you find yourself needing to search like this often. For example Beagle is a quite extensive search engine, it's been around for a while. Other options are KDE's Strigi or Google's Desktop Search

At the very least, you should use 'locate' instead of 'find', it only indexes file names and not their contents, but that will still speed things up. In addition you should filter based on file type before using grep. Eg using grep on a 100MB avi file or something is just a waste of time."
Guest [Entry]

"Yep, grep with the -r flag will search recursively. Try a command like:

grep -ri 'hello' .

Which will search the current directory, and every file and directory inside it, for the phrase 'hello'. The -i flag makes it case-independent, so it'll also find ""Hello"", ""HELLO"", etc."