266

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

codeforester
  • 39,467
  • 16
  • 112
  • 140
Rogers
  • 2,905
  • 3
  • 14
  • 11
  • 4
    Are you going to provide any feedback on the problems you encountered with `grep -r` or `grep -R`? Did you check the man page for `grep` on your machine? Did you remember to enclose the regex (string or text) in single quotes if it contains any metacharacters? – Jonathan Leffler Mar 25 '13 at 19:11

2 Answers2

476

If your grep supports -R, do:

grep -R 'string' dir/

If not, then use find:

find dir/ -type f -exec grep -H 'string' {} +
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
53
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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    I'm pretty sure SVR3.2 and SVR4 grep did not, as I worked on OS development for SYSV products during that time frame, and I had a rgrep shell script to wrap it at the time. I don't have one up any more to test on though. – Randy Howard Mar 25 '13 at 19:07
  • 8
    `-R` follows symlinks, which you may or may not want – James McMahon Feb 15 '14 at 21:01