Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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?

share|improve this question
    
Please don't cross-post. unix.stackexchange.com/q/82982/23363 –  gertvdijk Jul 14 '13 at 14:27
add comment

2 Answers

up vote 2 down vote accepted

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

grep -lr --include='*.c' search-pattern .
share|improve this answer
    
+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 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 at 8:00
add comment

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.)
share|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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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