Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I search a way to grep on source code without having sometimes false-positive because of comments. For instance if I search on foo on this .c source code :

/* 
 * foo has changed [...] and is now a 2-parameters function
 */
// foo(24)
foo(42, 28);

A naive grep will find 3 occurrences where I want only one. I have seen this way to do it on StackOverflow, but it does not fill my needs : PHP is not available on the platform. I have also found this way for one-line comments, but it only solves a part of my problem.

I need to use classical scripting tools (awk, sed, bash, grep, etc) and I need it to be fast even if there are thousands of files.

Do you now if and how it's possible to grep on source code, and only source code ?

share|improve this question
3  
Building a tags table might be a better approach, depending on what you're doing. –  Gilles Mar 1 '12 at 12:57
add comment

2 Answers

grep works on pure text and does not know anything about the underlying syntax of your C program. Therefore, in order not search inside comments you have several options:

  1. Strip C-comments before the search, you can do this using gcc -fpreprocessed -dD -E yourfile.c For details, please see http://stackoverflow.com/questions/2394017/remove-comments-from-c-c-code

  2. Write/use some hacky half-working scripts like you have already found (e.g. they work by skipping lines starting with // or /*) in order to handle the details of all possible C/C++ comments (again, see the previous link for some scary testcases). Then you still may have false positives, but you do not have to preprocess anything.

  3. Use more advanced tools for doing "semantic search" in the code. I have found "coccigrep": http://home.regit.org/software/coccigrep/ This kind of tools allows search for some specific language statements (i.e. an update of a structure with given name) and certainly they drop the comments.

share|improve this answer
add comment

You can try a naive approach to match non-comments like this:

 $ egrep -v "^(//|/\*| \*)" sourcecode

This will only inverse match against prefixed comments - that is lines starting with either //, /*, * or */ - and hence it'll not leave out blocks that are commented out with the /* and */ pair.

share|improve this answer
    
I am looking for a complete approach, not a naive one –  Coren Mar 1 '12 at 12:31
    
@Coren Sorry about that, I'm a naive person when it comes to computing B-) –  Herman Torjussen Mar 1 '12 at 15:59
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.