1

I m trying to change some characters in a file, like this:

//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;
}

I want to change all the // character for commenting in c++ to the c comment characters /* */ making the file then look like this:

/*  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;
}

I do not know much bash at all and this is what i came up with sed 's/////* *//g' myprog.c it did not work, what am i doing wrong or what do i need to do to make these changes? Im trying to make it a one line command

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

2 Answers2

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

But beware there are a number of cases where it wouldn't do the right thing like in:

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

To account for those cases and more, you could adapt the code at that other Q&A as:

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'

Which on the above sample gives:

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

You only need this:

 '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;
}