将c++中注释的所有//字符更改为c注释字符/* */

将c++中注释的所有//字符更改为c注释字符/* */

我正在尝试更改文件中的一些字符,如下所示:

//this is a thest of how this works
#include <stdio.h>

int main()
{
// declare some variables here
int num1 = 4;
float num2 = 3.5;

// print the result 
printf("The result is %f\n", num1 * num2); // this does it

/* does it work? */
return 0;
}

我想将 c++ 中用于注释的所有 // 字符更改为 c 注释字符 /* */ 使文件看起来像这样:

/*  This is a test of how this works */
#include <stdio.h>

/*this is a thest of how this works */
#include <stdio.h>

int main()
{
/* declare some variables here */
int num1 = 4;
float num2 = 3.5;

/* print the result  */
printf("The result is %f\n", num1 * num2); /* this does it */

/* does it work? */ */
return 0;
}

我根本不了解 bash,这就是我想出的 sed 's/////* *//g' myprog.c 它不起作用,我做错了什么或者我需要做什么做出这些改变?我试图使它成为一个单行命令

答案1

sed 's|//\(.*\)|/*\1 */|'

但要注意,在很多情况下它不会做正确的事情,例如:

char *url = "http://host/";
/*
   comment with // nested C++-syle comment
 */
// comment \
continued on the next line

为了考虑这些情况以及更多情况,您可以调整代码其他问答作为:

perl -0777 -pe '
  BEGIN{
    $bs=qr{(?:\\|\?\?/)};
    $lc=qr{(?:$bs\n|$bs\r\n?)}
  }
  s{
    /$lc*\*.*?\*$lc*/
    | /$lc*/((?:$lc|[^\r\n])*)
    | "(?:$bs$lc*.|.)*?"
    | '\''$lc*(?:$bs$lc*(?:\?\?.|.))?(?:\?\?.|.)*?'\''
    | \?\?'\''
    | .[^'\''"/?]*
  }{defined($1)?"/*$1 */":$&}exsg'

上面的示例给出了:

char *url = "http://host/";
/*
   comment with // nested C++-syle comment
 */
/* comment \
continued on the next line */

答案2

你只需要这个:

 's+//+/*+g' file | sed 's+\/\*.*+& */+'


/*this is a thest of how this works */
#include <stdio.h>

int main()
{
/* declare some variables here */
int num1 = 4;
float num2 = 3.5;

/* print the result  */
printf("The result is %f\n", num1 * num2); /* this does it */

/* does it work? */ */
return 0;
}

相关内容