Linux: Find Files by Name & Grep Contents

The Linux find command can be used for searching files and directories and performing subsequent operations on them.

If you use the find command to recursively search for some files and then pipe the result to the grep command, by doing this you will actually parse the file paths/names but not their contents.

This short note shows how to recursively find files by name and grep their contents for some word or pattern.

Cool Tip: How to match multiple patterns with -OR-, -AND-, -NOT- operators using grep! Read more →

Find Files by Name and Grep Contents in Linux

To find files by name and grep their contents use these commands as follows:

$ find <path> -type f -name '<fileName>' -exec grep -H "<text>" {} \;

For example, to find all files with the .log extension in the /var/log/ folder and grep their contents for the word “error” (with -i option, i.e. case-insensitive):

$ find /var/log/ -type f -name '*.log' -exec grep -H -i "error" {} \;
- sample output -
/var/log/Xorg.0.log:	(WW) warning, (EE) error, (NI) not implemented, (??) unknown.
/var/log/bootstrap.log:2021-07-03 11:21:26 ERROR 404: Not Found.
/var/log/bootstrap.log:2021-07-03 11:21:26 ERROR 404: Not Found.
...
Was it useful? Share this post with the world!

3 Replies to “Linux: Find Files by Name & Grep Contents”

  1. This can be done just using some flags of grep.

  2. Here it is:
    grep -r –include *.txt ‘pattern’
    finds pattern within .txt files, in current folder and below.

  3. Nick Fenwick says: Reply

    @ASDEL this fails for directories with too many files, for example our log directory contains many thousands of files, when the *.txt glob expansion fails.

    $ ls myDE*
    -bash: /usr/bin/ls: Argument list too long
    # Just to show that find can complete and give a list of files, note the quotes avoiding glob exansion on the find command line.
    $ find . -name “myDE*” | wc -l
    164726

    The approach using find and asking it to exec grep for each file found works well. If you don’t want to recurse into subdirectories, you can use the -depth argument.

Leave a Reply