0

Suppose I have the following file called Test.java:

import java.io.*;

/* test comment */
public class Test { /* another test comment */
    ...
    ...
    ...
}

Java programs can contain single-line // comments and multi-line /* ... */ comments. What I am trying to accomplish is to find /* ... */ comments in Test.java that occupy a single line and replaces them with a // comment, in place. So, after replacement, Test.java should look like this:

import java.io.*;

// test comment
public class Test { // another test comment
    ...
    ...
    ...
}

I tried to do this with sed by doing the following:

sed -ri 's//\* ([.]*[ ]*) \*//// \1/' Test.java

However, it doesn't seem to change anything. Due to this, I was wondering how do I just replace comments while keeping the rest of the line unchanged? I'm unsure how to accomplish this behavior. I think my regex is off somehow, but I'm not entirely sure why. Any feedback or suggestions would be greatly appreciated.

1

This will do it:

sed 's_/\*\(.*\)\*/_//\1_' <Test.java

The ways it's working is as follows:

  • I'm using the _ as a delimiter so I don't have to escape the / characters
  • '/*' is matched with /\* (escaping the *)
  • I remember the stuff in between the above using \( and \)
  • then replace with '//' (no need to escape) and the remembered content \1

Once you've confirmed it does what you want, just add the -i and remove the <:

sed -i 's_/\*\(.*\)\*/_//\1_' Test.java
0

I suspect your second bullet point was meant to be:

'/*' is matched with /\* (escaping the *) and '*/' is matched 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.