Finding text within files on Linux

So at some point in your professional life, you have probably faced the following problem:

I have a bunch of files and I want to quickly find a file that contains a particular text. I don’t want to go through each file individually because that’s lame. Also, I don’t want to use GUI because I aspire to become pro at using Linux commands.

Yeah, yeah we’ve all been there. As a beginner, I struggled a lot with this and even if I found a solution, I won’t be able to recall it the next time when I’d so desperately need it. Well, here it is!

If you are looking in all files whose name ends with .txt:

find /home/manthan/folder_o_files -name *.txt -type f -exec grep awesome {} \; -print;

In the above command, we’re looking through all the files (denoted by -type f) in /home/manthan/folder_o_files folder. The -exec flag allows user to specify what command to execute for line of output from the find command. In this case, we’re using our favourite command grep to find for text awesome. The opening and closing curly brackets (denoted by {}) serve as placeholder for each line of file outputted by the find command. We escape the semi-colon to end the grep command, ask find command to show its findings by supplying it with -print flag and then terminate our command by ending it with semi-colon.

If you are unsure of the case of the text (i.e. upper-case or lower-case), stick -i flag right after grep.

If for some reason you are looking through a bunch of tar files and are looking for a file that one of the tar files might contain, check out my other post on How to find a file contained with a bunch of tar files without opening (soon).

Enjoy!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.