Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

regex - How can I delete all /* */ comments from a C source file?

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++)

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Why not just use the c preprocessor to do this? Why are you confining yourself to a home-grown regex?

[Edit] This approach also handles Barts printf(".../*...") scenario cleanly

Example:

[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?

[Edit] If you want to not expand included files and macroa by this approach, cpp provides flags for this. Consider:

[File: 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...