14

Let's say I need to find the function GetTypes() in all C# source file (.cs) the directories/subdirectories.

I used grep -rn GetTypes *.cs, but I got an error with grep: *.cs: No such file or directory. I had to use grep -rn GetTypes *, but in this case it shows all the files not *.cs only.

What command do I need to use to find the string only in .cs files?

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
prosseek
  • 8,418
  • 16
  • 47
  • 43
  • possible duplicate of [Finding a substring in files across subdirectories with a single built-in command?](http://unix.stackexchange.com/questions/7383/finding-a-substring-in-files-across-subdirectories-with-a-single-built-in-comman) – Gilles 'SO- stop being evil' Mar 28 '12 at 23:24

4 Answers4

16

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 {} +
Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
  • To temporary set the `globstar` option for a current Bash 4+ shell, use: `shopt -s globstar`. – tjanez Sep 21 '17 at 13:35
8

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
Caleb
  • 69,278
  • 18
  • 196
  • 226
6

If you use GNU grep, you can specify which files to include in a recursive directory traversal:

grep --include '*.cs' -rn GetTypes .

(where the last period denotes the current working directory as root of the traversal)

maxschlepzig
  • 56,316
  • 50
  • 205
  • 279
4

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.

Kevin
  • 40,087
  • 16
  • 88
  • 112
Kevin
  • 41
  • 1