Author - Web Developer - Educator
RSS Feed

Find text in files with GREP

I needed to reference this quite frequently, so I thought I'd post it here.

Ever had the frustration of needing to find a certain string inside files on a Linux OS via a terminal/command line? It'd be nice to have something like the Windows File Finder (when it works) to search for text inside of a file and report the file back.

You could cat each file and use grep [string] to spit back each line, then write down the filename. But there is an easier way.

Use grep first instead of piping it!

All you need to do is type in

grep -lir "[phrase]" [directory]
and that's all there is to it (the quotations are optional). By using the command grep instead of using it after a pipe "|", this can search through files in an instant instead of having to manually search through each file. The -l (that's a lowercase "L") puts out files that match (as opposed to -v which shows all files that don't match). The i makes the search query case insensitive. Lastly, the r makes grep recursive in folders. Simple as that. Of course, you can have the results spit back to you if you just press Enter, or you can output it to a file by using the > operator, like so:
grep -lir "cout" . > output.txt
(my VB and C++ friends should like this)

Tags:#linux #commandline #terminal #grep #search #tutorials