How to grep a string in a directory and all its subdirectories?

LinuxUnixGrepCentos

Linux Problem Overview


How to grep a string or a text in a directory and all its subdirectories'files in LINUX ??

Linux Solutions


Solution 1 - Linux

If your grep supports -R, do:

grep -R 'string' dir/

If not, then use find:

find dir/ -type f -exec grep -H 'string' {} +

Solution 2 - Linux

grep -r -e string directory

-r is for recursive; -e is optional but its argument specifies the regex to search for. Interestingly, POSIX grep is not required to support -r (or -R), but I'm practically certain that System V grep did, so in practice they (almost) all do. Some versions of grep support -R as well as (or conceivably instead of) -r; AFAICT, it means the same thing.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRogersView Question on Stackoverflow
Solution 1 - LinuxJohn KugelmanView Answer on Stackoverflow
Solution 2 - LinuxJonathan LefflerView Answer on Stackoverflow