从C文件中提取头文件名的正则表达式

3
如何从包含如下所示头文件的C文件中提取头文件?
```c #include #include ```
#include <tema4header9.h>
#include    <tema4header3.h>
#include   <stdio.h>
#include        <longnametest/newheader.h>
#include <net/header.h>
#include  "last-test-Zhy3/DrRuheader.h"
#include <last-test-8fF7/a5xyheader.h>

我尝试使用: sed -n -e 's/#include[ \t]*[<"]\([^ \/<"]*\/[^ \/]*\)\.h[">]/\1\.h/p' 但它只适用于子目录中的文件。如果我输入: sed -n -e 's/#include[ \t]*[<"]\(([^ \/<"]*\/)+[^ \/]*\)\.h[">]/\1\.h/p' 或者 sed -n -e 's/#include[ \t]*[<"]\(([^ \/<"]*\/)*[^ \/]*\)\.h[">]/\1\.h/p' 该命令将不再起作用。输出文件应如下所示:
tema4header9.h
tema4header3.
stdio.h
longnametest/newheader.h
net/header.h
last-test-Zhy3/DrRuheader.h
last-test-8fF7/a5xyheader.h

你期望的输出是什么?tema4header9.h等等? - Inian
4个回答

2

grep 解决方案:使用 Perl 正则表达式,并在以 #include 开头的行上打印介于 "<"'"' 之间的任何内容。

grep -oP '^#include.*(<|")\K.*(?=>|")' headers
tema4header9.h
tema4header3.h
stdio.h
longnametest/newheader.h
net/header.h
last-test-Zhy3/DrRuheader.h
last-test-8fF7/a5xyheader.h

如果您熟悉 awk,那么:
awk '/#include/{gsub(/<|>|"/,"",$2);print $2}' headers
tema4header9.h
tema4header3.h
stdio.h
longnametest/newheader.h
net/header.h
last-test-Zhy3/DrRuheader.h
last-test-8fF7/a5xyheader.h

只需使用grep,就足以使用'(?<="|\<).*(?="|\>)' - Inian
@Inian,它可能会从file.c中提取一些不需要的行中提取数据,例如 cout << "hey there" << "x>y" <<endl;,因此添加了#include作为安全措施。这取决于OP来判断风险。 - P....
我指的是在引号和 < 中提取部分,同意之前的部分是必要的。 - Inian
有人能告诉我如何为C++ regex_search编写类似grep的正则表达式吗? - Aditya kumar
警告:这些模式无法捕获所有的 #include。在 C/C++ 中,允许在 # 周围使用空格和制表符。例如:# include <header.h>。正确的写法是:grep -oE '^[ \t]*#[ \t]*include[ \t]*(<[^<]*>|"[^"]*")' headers - Dr. Alex RE

1
这应该可以工作:

sed -nr 's/#include\s+[<"]([^>"]+)[>"].*/\1/p'

0

尝试:

awk '{match($0,/[<"].*[>"]/);print substr($0,RSTART+1,RLENGTH-2)}' Input_file

0

像上面一样:

sed -n 's/\s*#\s*include\s*[<"]\(.\+.h\)[>"]/\1/p' input_file

但这更加精确,例如,input_file 的内容为:

 # include <stdio.h>
       #        include<stdlib.h>
    #    include    <time.h>
 #define LEN 8
 #define OPT 2
 #include <pthread.h>
 # include "mysql.h"
 #include "paths.h"

它仍然可以正确打印:

stdio.h
stdlib.h
time.h
pthread.h
mysql.h
paths.h

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接