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{
field1;
field2; /** comment 1
*/ field3;
/* comment 2 */
} struct_name;
I need to get
struct my_struct{
field1;
field2;
field3;
} 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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can do it with a C compiler : gcc :
gcc -fpreprocessed -dD -E -P file.c
check man gcc
Method 2
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
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0