如何删除从C源文件中的所有/ * * /注释吗? [英] How can I delete all /* */ comments from a C source file?
问题描述
我有我从别的地方复制了C文件,但它有很多的类似下面的评论:
I have a C file which I copied from somewhere else, but it has a lot of comments like below:
int matrix[20];
/* generate data */
for (index = 0 ;index < 20; index++)
matrix[index] = index + 1;
/* print original data */
for (index = 0; index < 5 ;index++)
我怎样可以删除 / *
和包围的所有注释* /
。有时,意见
是由4-5行,我需要删除所有这些行。
How can I delete all the comments enclosed by /*
and */
. Sometimes, the comments
are consist of 4-5 lines, and i need to delete all those lines.
基本上,我需要删除 / *
和 * /
,甚至 \\ n
可以进来的。请帮我做到这一点使用 SED
, AWK
中的一个或 perl的
。
Basically, I need to delete all text between /*
and */
and even \n
can come in between. Please help me do this using one of sed
, awk
or perl
.
推荐答案
为什么不直接使用C preprocessor做到这一点?你为什么要限制自己一个土生土长的正则表达式?
Why not just use the c preprocessor to do this? Why are you confining yourself to a home-grown regex?
这种方法还可以处理的Barts 的printf(... / * ...)
情景干净
This approach also handles Barts printf(".../*...")
scenario cleanly
例如:
[File: t.c]
/* This is a comment */
int main () {
/*
* This
* is
* a
* multiline
* comment
*/
int f = 42;
/*
* More comments
*/
return 0;
}
$ cpp -P t.c
int main () {
int f = 42;
return 0;
}
或者,您可以删除空格和凝聚一切
Or you can remove the whitespace and condense everything
$ cpp -P t.c | egrep -v "^[ \t]*$"
int main () {
int f = 42;
return 0;
}
没有使用重新发明轮子,有没有?
No use re-inventing the wheel, is there?
如果你想的不的通过这种方式扩大包含的文件和macroa, CPP
提供标志这一点。试想一下:
If you want to not expand included files and macroa by this approach, cpp
provides flags for this. Consider:
[文件:T.C]
#include <stdio.h>
int main () {
int f = 42;
printf(" /* ");
printf(" */ ");
return 0;
}
$ cpp -P -fpreprocessed t.c | grep -v "^[ \t]*$"
#include <stdio.h>
int main () {
int f = 42;
printf(" /* ");
printf(" */ ");
return 0;
}
有是的可避免在宏扩展轻微的警告,但宏的原始定义是从源头上剥离。
There is a slight caveat in that macro expansion can be avoided, but the original definition of the macro is stripped from the source.
这篇关于如何删除从C源文件中的所有/ * * /注释吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!