Replacing and Adding Text at the End of Lines with Sed

sed

I have a line as follows

 // Testing this

I am trying to use a sed command to replace the // with a /* (sentence or word in between) */ on each line.

so it should look something like this

/* Testing this */

The first part is easy with calling

sed 's#//#/*#'

however, with the second part, I tried this solution

Appending word at the end of line with sed [duplicate]

I tried with -e which gave me an error of 'unterminated s command'. Then, I tried with a semi colon to make it one so it was something along the lines of

's#//#/*#;#//#s#/$#*/#'

but all that seems to do is the first part (replacing // with /*)and not the second (putting a */ at the end of the same line).

What am I not doing correctly? Any pointers would be appreciated.

Best Answer

How about

$ cat testfile
// Testing this
foobar
$ sed 'sx//\(.*\)x/*\1 */x' testfile
/* Testing this */
foobar
$
  • sx// : search for lines containing //
  • \(.*\)x : place the remaining part of the line into capture group 1
  • /*\1 */x : replace the remaining part of the line with /* (start of comment, C-style) followed by the contents of the capture group 1 (referenced as \1), followed by */ (end of comment, C-style)
Related Question