grep:在用户包含文件中搜索

时间:2014-02-20 05:11:31

标签: include grep

我想使用 grep 或find来搜索某些c文件中的字符串/表达式。有没有办法搜索包含在该c文件中的头文件?

例如:

myfile.c文件

#include <stdio.h>
#include "myfile1.h"
#include "myfile2.h"

void main()
{
   DATA val;  
}

我想搜索字符串“DATA”。它应该在myfile.c和myfile1.h,myfile2.h中搜索......

2 个答案:

答案 0 :(得分:0)

我觉得这样的事情可能有用:

grep -nr "DATA" path/to/files
  • n将包含匹配的文件的行号
  • r将在提供的路径上递归搜索

您还可以专门列出每个文件:

grep -nr "DATA" myfile.c myfile1.h myfile2.h

或者,如果您的所有.h文件都在同一目录中:

grep -nr "DATA" *.h

此外,您可以grep获取包含的头文件列表:

grep -o "\".*\.h\"" myfile.c
"myfile1.h"
"myfile2.h"

从那里,您可以使用xargs获取这些输出并对返回的每个文件名运行原始搜索:

grep -o "\".*\.h\"" myfile.c | xargs grep -n "DATA"

如果您愿意,也可以在搜索中包含原始文件:

grep -o "\".*\.h\"" myfile.c | xargs grep -n "DATA" myfile.c

答案 1 :(得分:0)

编写一个shell脚本,就像这样

1)首先在myfile.c中搜索单词DATA

grep -nr "DATA" myfile.c

2)搜索包含扩展名.h

的单词

3)现在再次将grep命令应用于这些头文件

grep -nr "DATA" myfile1.h myfile2.h