I am trying to remove comments from a file which may be in any part of a line and span multiple lines.

 struct my_struct{
  field2; /** comment 1
  */ field3;
  /* comment 2 */
 } struct_name;

I need to get

struct my_struct{
 } struct_name;

I tried using

grep -o '[^/*]*[^*/]' 

to remove any text between matching /* and */, but it is eliminating the comment symbols but not the text in between. What is the correct way? If there is another way using 'sed', it would be nice to know that too.

marked as duplicate by don_crissti, roaima, Jeff Schaller, drewbenn, countermode Oct 20 '16 at 21:35

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


If you just want to remove anything between /* and */, and ignore all the quirks of the C language, like C99-style //-comments, quoted strings and backslash-escapes of newlines, then a simple Perl-regex should do:

perl -0777 -pe 's,/\*.*?\*/,,gs' inputfile

You can do it with a C compiler : :

gcc -fpreprocessed -dD -E -P file.c

check man gcc

Not the answer you're looking for? Browse other questions tagged or ask your own question.