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.
...

Leave a Reply