Skip to main content
4 of 5
added 190 characters in body

Removing c-style comments with sed

I need to delete some kind of characteristic, single line C++ comments from all files in our repository. Code looks something like this:

some_code
// characteristic_comment_to_delete
some_more_code // another_comment
another_line_with_code // characteristic_comment_to_delete
even_more_code

As a result, I would like to get this:

some_code
some_more_code // another_comment
another_line_with_code
even_more_code

I used sed command that makes my result almost as good as I would like:

$sed -i -e 's&// characteristic_comment_to_delete.*&&g' some_file.cpp
some_code

some_more_code // another_comment
another_line_with_code
even_more_code

Unfortunately, leaving those blank lines is unacceptable solution, so I need somehow improve my command so that it removes whole line, but only if it is left blank after removing this specific comment.

EDIT: I obviously did not run those commands as root. Changed prompt accordingly. Also, I did not want to remove all comments, so I do not think that my topic is duplicating other threads.