1

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.

  • Are you trying to convert C++-style comments to C-style comments ? – don_crissti Sep 23 '18 at 21:34
  • @don_crissti yes but I want to know in general. I have other files where I have to replace phone numbers and add things to the end of them so I am trying to figure out how to do it in general. – TheRealPdGaming Sep 23 '18 at 21:48
0

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)
  • 1
    Thank you for the explanation. Do you mind me asking, what is the (.*) is for in this case? I realize the " ( " and " ) " are escape sequences for the parenthesis, but what are we doing with the " .* " ? PS: I don't know why the backslash character is not showing up. – TheRealPdGaming Sep 24 '18 at 2:48
  • Sure, elaborated. – steve Sep 25 '18 at 21:35
0

Another approach: make the search and replace conditional on the comment being matched at all:

sed '\!//! {s!!/*!; s!$! */!}' file

That reads:

  • if the line contains the pattern //, then
    • replace the matched text with /*
    • and then replace the empty string at end of line with */

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.