Find a string only in a specific file inside subdirectories
If your shell is bash ≥4, put shopt -s globstar
in your ~/.bashrc
. If your shell is zsh, you're good. Then you can run
grep -n GetTypes **/*.cs
**/*.cs
means all the files matching *.cs
in the current directory, or in its subdirectories, recursively.
If you're not running a shell that supports **
but your grep supports --include
, you can do a recursive grep and tell grep
to only consider files matching certain patterns. Note the quotes around the file name pattern: it's interpreted by grep, not by the shell.
grep -rn --include='*.cs' GetTypes .
With only portable tools (some systems don't have grep -r
at all), use find
for the directory traversal part, and grep
for the text search part.
find . -name '*.cs' -exec grep -n GetTypes {} +
You should check out the billiant little grep/find replacement known as ack
. It is specifically setup for searching through directories of source code files.
Your command would look like this:
ack --csharp GetTypes
I'm using a combination of find and grep:
find . -name "*.cs" | xargs grep "GetTypes" -bn --color=auto
For find
, you can replace .
by a directory and remove -name
if you want to look in every file.
For grep
, -bn
will print the position and the line number and --color
will help your eyes by highlighting what you are looking for.