This is the command that I am trying to run.

grep -r "printf" *.c

I am trying to get all the printf lines from all .c files present in my cwd. As of now, my current directory is Desktop, and I have at least 10-15 .c files in my sub-directories under Desktop, but this command doesn't show any matches at all. So how do I make this work in this case?

2 Answers 2


If you do:

grep -r "printf" *.c

the shell will expand *.c to all files/directories ending in .c in your current directory, if no such file/directory exists, the pattern will be treated literally (presumably you don't have nullglob set).

As you can see, your current pattern is never going beneath the current directory as you don't have any .c file in the current directory or if there are any, they don't have printf in them, leading to the empty output.

You need to use --include to search in selective files only, and also -r to traverse recursively:

grep -r --include="*.c" "printf" .

The above will search in all .c files for the string (pattern) printf, recursively starting from the current directory.

if you want to follow all symlinks:

grep -R --include="*.c" "printf" .

If you want to know why your command doesn't work, see the other answer.  If you want to know how to make it work, here's another approach (copied from Grep in files with a specific extension under a directory with cosmetic localizations) that uses the capabilities of bash rather than the capabilities of grep (and therefore will work for any command, such as wc, cp or tar, and not just grep):

Set (turn on) the shell option globstar with the command

shopt -s globstar

This will cause ** as a filename component to mean everything here and below.  So, if you're in Desktop, then ** means everything in the Desktop directory and its subdirectories.  Then you can use

grep "printf" **/*.c

to search all the .c files in and under Desktop.  You don't need to specify -r, because the shell does the recursion for you, and you don't need to specify --include, because the pathname expansion pattern (a.k.a. glob or wildcard) contains *.c.

You can unset options with shopt -u.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .