sed replace (single-line) C comments with C++ comments

时间:2022-09-13 16:19:26

How can i use sed to replace all my C-style comments in a source file to C++ style.

我如何使用sed将源文件中的所有C风格注释替换为C ++风格。

All these:

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

to:

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

All comments are single line and there are none in between code like this:

所有注释都是单行的,代码之间没有这样的注释:

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's expression syntax. Since "." matches any character and " * " matches zero or more of some pattern. I assume ".*" matches any number of any character.

但它保持文件不变。这篇文章很相似,但我试图理解sed的表达式语法。自“。”匹配任何字符,“*”匹配某些模式的零个或多个。我假设“。*”匹配任何数字的任何字符。

1 个解决方案

#1


5  

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

this will transform each line like this :

这会像这样改变每一行:

aaa  /* test */

into a line like this:

成这样的一行:

aaa  // test

If you have more comments on the same line, you can apply this more sophisticated parser, that converts a line like:

如果您在同一行上有更多注释,则可以应用此更复杂的解析器,该解析器转换如下行:

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

into

aaa  bbb ccc // c1 c2

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

A more sophisticated case is when you have comments inside strings on a line, like in call("/*string*/"). Here is a script c-comments.sed, to solve this problem:

更复杂的情况是当你在一行的字符串中有注释时,比如在call(“/ * string * /”)中。这是一个脚本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 into a file c-comments.sed, and you call it like this:

您将此脚本保存到文件c-comments.sed中,并将其称为:

sed -i -f c-comments.sed FILE

#1


5  

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

this will transform each line like this :

这会像这样改变每一行:

aaa  /* test */

into a line like this:

成这样的一行:

aaa  // test

If you have more comments on the same line, you can apply this more sophisticated parser, that converts a line like:

如果您在同一行上有更多注释,则可以应用此更复杂的解析器,该解析器转换如下行:

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

into

aaa  bbb ccc // c1 c2

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

A more sophisticated case is when you have comments inside strings on a line, like in call("/*string*/"). Here is a script c-comments.sed, to solve this problem:

更复杂的情况是当你在一行的字符串中有注释时,比如在call(“/ * string * /”)中。这是一个脚本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 into a file c-comments.sed, and you call it like this:

您将此脚本保存到文件c-comments.sed中,并将其称为:

sed -i -f c-comments.sed FILE