Find file containing text in linux

In this post, we will see how to find files containing specific text.

Problem

You want to search for any specific text in all the files in a directory.

Solution

There are lots and lots of files on linux or unix server. You can find and locate a file using find command but it is not possible to look inside a text file for specific text.

You can use grep command. Grep command searches given inputs files for line containing specified text.


1. Search text "https://www.google.com" in current directory

grep -s “text to be searched” *

Run example:

$ grep -s “https://www.google.com” *

site.txt:https://www.google.com is awesome search engine


2. Search text "https://www.google.com" in current directory and all subdirectories

grep -r “https://www.google.com” *

3. Search text "https://www.google.com" in current directory,all subdirectories and display matched text in color

grep -r –color “https://www.google.com” *

4. Search text "https://www.google.com" in /opt directory and display just file name

By default, grep prints file name and line containing text in a file. If you just want to display file name, you can use below command.

grep -r “https://www.google.com” /opt/*| cut -d: -f1

5. Hide warning spam

By default, grep prints file name and line containing text in a file. If you just want to display file name, you can use below grep command generates lots of error message due to permission issues such as

No such file or directory
No such device or address
Permission denied

Sometimes, you get so many errors that it is hard to find actual file.To hide all error or warning message, append 2>/dev/null to grep command. This will send and hide unwanted outut to /dev/null.

grep -r “https://www.google.com” /opt/* 2>/dev/null

6. Ignore case while searching text

If you want to do case insensitive search, then use -i option with grep.

grep -r -i “https://www.google.com” *

That’s all about how to find file containing text in linux

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *