从C文件中提取标题名称的正则表达式
问题描述:
如何从包含这样的头文件的c文件中提取头文件?
How to extract headers from a c file that contains them like this?
#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'
,但仅适用于子目录中的那些.另外,如果我输入:
but it only works for those in subdirectories. also if i type:
sed -n -e 's/#include[ \t]*[<"]\(([^ \/<"]*\/)+[^ \/]*\)\.h[">]/\1\.h/p'
或
sed -n -e 's/#include[ \t]*[<"]\(([^ \/<"]*\/)*[^ \/]*\)\.h[">]/\1\.h/p'
该命令不再起作用.输出文件应如下所示:
the command does not work anymore. The output file should look like this:
tema4header9.h
tema4header3.
stdio.h
longnametest/newheader.h
net/header.h
last-test-Zhy3/DrRuheader.h
last-test-8fF7/a5xyheader.h
答
grep
解决方案:这是使用perl正则表达式,并在以#include
开头的行上打印"<"
或'"'
之间的任何内容.
grep
solution: This is using perl regex and printing anything between "<"
or '"'
on the lines which start with #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