259

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

codeforester
  • 34,080
  • 14
  • 96
  • 122
Rogers
  • 2,825
  • 3
  • 13
  • 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

457

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
  • 330,190
  • 66
  • 504
  • 555
50
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
  • 698,132
  • 130
  • 858
  • 1,229
  • 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
  • 7
    `-R` follows symlinks, which you may or may not want – James McMahon Feb 15 '14 at 21:01