I tried to recursively search a pattern in all the .c files in the following way

> grep -lr search-pattern *.c

But got this as the output

> grep: *.c: No such file or directory

When I use this:

> grep -lr search-pattern *

I get plenty of . c files in the directories with the pattern.

What is wrong with the earlier expression?


I suggest to use the --include option of grep:

grep -lr --include='*.c' search-pattern .
| improve this answer | |
  • 1
    +1. I didn't know the --include=GLOB option. In combination with the recursive option this is very powerful and doesn't require find. Nice! – gertvdijk Jul 14 '13 at 14:13
  • Late to the party here, but I'm confused about what the . at the end of the command is for. – Nathan Jones Feb 5 '14 at 21:28
  • 1
    @NathanJones: grep requires one or more filenames or directories in which to search. The dot says: search in the current directory – enzotib Feb 6 '14 at 8:00

The *.c pattern is evaluated by your shell. It applies to the current directory, just like you would using ls *.c.

I think what you want instead is to find all files matching the *.c pattern (recursively) and have grep search for you in it. Here's a way to do that:

find . -name "*.c" -print0 | xargs --null grep -l search-pattern

It uses xargs to append the search results by find.

Alternatively, use the -exec option to find, e.g.:

find . -name "*.c" -exec grep -l search-pattern "{}" \;

Also, I'm not sure if you really want the -l option to grep. It will stop at the first match:

-l, --files-with-matches
      Suppress normal output; instead print the name of  each
      input  file  from which output would normally have been
      printed.  The scanning will stop on  the  first  match.
      (-l is specified by POSIX.)
| improve this answer | |
  • The find/xargs syntax breaks on filenames containing spaces. The -L option of grep stop on first match of each file and continue with next file: if one only want to see if the pattern is contained at least once in each given file, it is quicker. – enzotib Jul 14 '13 at 14:12
  • @enzotib Thanks, fixed it using -print0 option and xargs --null. – gertvdijk Jul 14 '13 at 14:17

I know this is a rather old thread, but since I had the same question, I wanna share my preferred way of acheiving the same, In a much shorter form.

ls | grep "file.*.c"
| improve this answer | |
  • 2
    The question is about searching for a pattern not about searching a file. – Jay Sep 19 '19 at 15:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.