# Ubuntu – Why does this grep for a string in all sub directories not work

command linedirectorygrep

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?

#### Best Answer

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