How to search all the files in a directory for a specific string

Hi Guys,

I want to search the content of all the files (of a particular type like .txt)
in a directory for a specific string pattern. Can anyone help me?

Thanks

grep "string" *.txt

should do you ?

Thanks. how can i search all the sub directories?

If you have GNU grep:

grep -r 'string' *.txt

Otherwise:

find . -type f -name '*.txt' -print | xargs grep 'string'
grep -i "string" `find ./ -name "*.txt"`

That approach has 2 potential problems:

  1. The *.txt glob will be expanded if there are files with the txt extension in the current directory, screwing up the find command.
  2. If find returns too many files, grep/the shell will refuse running and complain about a too large argument list

Also, I'd advise anyone against using backticks and use the $() construct instead, as it's less likely to be misinterpreted, and can be nested multiple times.

Thanks a lot Pludi :b:

egad... use the built in find exec command, this is what it was designed for,
although the xargs solution should work also.

find . -name \*.txt -type f -exec grep some-string {} \; -print