273

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

1
  • 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? Commented Mar 25, 2013 at 19:11

2 Answers 2

487

If your grep supports -R, do:

grep -R 'string' dir/

If not, then use find:

find dir/ -type f -exec grep -H 'string' {} +
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

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.
-R follows symlinks, which you may or may not want

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.