如何在不捕获注释的情况下对源代码进行 grep

Cor*_*ren 11 grep source files

我搜索了一种对源代码进行 grep 的方法,而不会因为评论而有时误报。例如,如果我在这个 .c 源代码上搜索 foo :

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

一个天真的grep会发现 3 次我只想要一个。我在 StackOverflow 上看到过这种方法,但它不能满足我的需求:PHP 在平台上不可用。我也为单行注释找到了这种方式,但它只能解决我的一部分问题。

我需要使用经典的脚本工具(awk、sed、bash、grep 等),并且即使有数千个文件,我也需要它很快

您现在是否以及如何可以对源代码进行 grep,并且仅对源代码进行 grep?

dyi*_*ynx 12

grep 处理纯文本,对 C 程序的底层语法一无所知。因此,为了不在评论中搜索,您有多种选择:

  1. 在搜索之前去掉 C 注释,您可以使用它来执行此操作gcc -fpreprocessed -dD -E yourfile.c有关详细信息,请参阅/sf/ask/167581221/

  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.


小智 10

您可以尝试一种天真的方法来匹配这样的非注释:

 $ egrep -v "^(//|/\*| \*)" sourcecode
Run Code Online (Sandbox Code Playgroud)

这将打击前缀评论仅供逆匹配-这是开始的行任一///***/-因此它会不会离开了与该注释掉块/**/对。