Comments on C ++ comments (single-line) with C ++ comments

How can I use sed to replace all my C style comments in the source file with C ++ style.

All this:

int main() { /* some comments */ ... 

in

 int main() { // some comments ... 

All comments are a separate line and between the code does not exist:

 int f(int x /*x-coordinate*/ ); 

so i tried this:

  sed -i 's/ \/\* .* \*\ / \/\/* /g' src.c 

but it leaves the file unchanged. This post is similar, but I'm trying to understand sed syntax syntax. Because the "." matches any character, and "*" matches zero or more of some pattern. I assume that ". *" Matches any number of any character.

+4
source share
1 answer
 sed -i 's:\(.*\)/[*]\(.*\)[*]/:\1 // \2:' FILE 

this converts each line as follows:

 aaa /* test */ 

to a line like this:

 aaa // test 

If you have more comments on one line, you can apply this more complex parser, which converts the line, for example:

 aaa /* c1 */ bbb /* c2 */ ccc 

in

 aaa bbb ccc // c1 c2 

 sed -i ':rs:\(.*\)/[*]\(.*\)[*]/\(.*\):\1\3 //\2:;tr;s://\(.*\)//\(.*\)://\2\1:;tr' FILE 

A more complicated case is when you have comments inside lines in a line, for example, in call("/*string*/") . To solve this problem, there is a script c-comments.sed :

 s:\(["][^"]*["]\):\n\1\n:g s:/[*]:\n&:g s:[*]/:&\n:g :r s:["]\([^\n]*\)\n\([^"]*\)":"\1\2":g tr :x s:\(.*\)\n/[*]\([^\n]*\)[*]/\n\(.*\)$:\1\3 // \2: s:\(.*\)\n\(.*\)//\(.*\)//\(.*\):\1\n\2 //\4\3: tx s:\n::g 

You save this script to the c-comments.sed file, and you call it like this:

 sed -i -f c-comments.sed FILE 
+5
source

All Articles