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.

2 Answers 2

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 \*/

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .