1

This question is an exact duplicate of:

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

marked as duplicate by don_crissti, Jeff Schaller, user88036, andcoz, Romeo Ninov Oct 8 '18 at 15:28

This question was marked as an exact duplicate of an existing question.

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;
}
  • anchoring the // misses the // this does it comment – Jeff Schaller Oct 8 '18 at 14:33
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 */