如何从 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.
基本上,我需要删除 /*
和 */
之间的所有文本,甚至
也可以介于两者之间.请使用 sed
、awk
或 perl
之一帮助我做到这一点.
Basically, I need to delete all text between /*
and */
and even
can come in between. Please help me do this using one of sed
, awk
or perl
.
推荐答案
为什么不直接使用 c 预处理器来执行此操作?你为什么要把自己局限在一个本土的正则表达式中?
Why not just use the c preprocessor to do this? Why are you confining yourself to a home-grown regex?
[Edit] 这种方法也可以干净地处理 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 "^[ ]*$"
int main () {
int f = 42;
return 0;
}
重新发明轮子没有用,是吗?
No use re-inventing the wheel, is there?
如果您想不通过这种方法扩展包含的文件和宏,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 "^[ ]*$"
#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屋!