6

Linux: Find Files by Name & Grep Contents

 2 years ago
source link: https://www.shellhacks.com/linux-find-files-by-name-grep-contents/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK