kirakun
kirakun

Reputation: 2790

Sed to replace multiline Java comment with another text

I have some java code:

/**
 * Some comment.
 */
void someFunction();

/**
 * Some comment.
 */
void anotherFunction();

How to write a single line sed to convert the above into

@Override
void someFunction();

@Override
void anotherFunction();

The best I could do is to just delete the comments with

sed '/\/\*\*/,/\*\// d'

and manually insert @Override.

EDIT: The method signature is not always void().

Upvotes: 1

Views: 1124

Answers (3)

fedorqui
fedorqui

Reputation: 290025

If you can also work with awk, this can make it:

$ awk '/\/\*/ {p=0; next} /\*\// {p=1; print "@Override"; next}p' file
@Override
void someFunction();

@Override
void anotherFunction();

@Override
char Bla();

For a given file

/**
 * Some comment.
 */
void someFunction();

/**
 * Some comment.
 */
void anotherFunction();

/**
 * Some comment.
 */
char Bla();

Upvotes: 1

Andrew Clark
Andrew Clark

Reputation: 208545

Here is how you can do this with a single pass of sed:

sed '/\/\*\*/,/\*\// {s/.*\*\/.*/@Override/p; d}'

The commands within the braces will only run for the lines that are a part of the comment, and the s/.*\*\/.*/@Override/p will only match the end of the comment and then print @Override as desired.

Upvotes: 1

dganesh2002
dganesh2002

Reputation: 2220

You can use sed to insert a new line after '*/'

sed '/\*\// a @Override' file

and then run your command -

sed '/\/\*\*/,/\*\// d' file

This way you can add @override for each method even if it doesn't start with void. But There should be comment section for each method.

Upvotes: 1

Related Questions