Reputation: 3036
How can i use sed to replace all my C-style comments in a source file to C++ style.
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.
Upvotes: 6
Views: 3683
Reputation: 15793
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:
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:
sed -i -f c-comments.sed FILE
Upvotes: 6