1

I'm new to sed and I can't manage to use it to remove all ';' characters in comments of C++ files, ie lines starting or containing the string "//" (I already convert "/* ... */" comments to "// ..." comments).

For example :

// lorem; ipsum ; test
int a; // 1 ; 2 ; 3 ;

And I want to have :

// lorem ipsum  test
int a; // 1  2  3 

For any comment in my C++ files.

********* EDIT *********

Here is a solution with SED in two steps. A solution with AWK is also available in answers.

  1. Put all comments on a new line : sed 's/\/\//\n\/\//g'
  2. Remove ';' only on lines starting by "//" : sed '/^\/\// s/;//g'
Iwaa
  • 13
  • 3

1 Answers1

0

It is straightforward in AWK. Create a file r.awk:

function process(s) {
    gsub(";", "", s)
    return s
}

{
    sep = "//"; ns=length(sep)
    m = match($0, sep)
    if (!m) {print; next}

    body = substr($0,    1, m-1)
    cmnt = substr($0, m+ns     )

    print body sep process(cmnt)
}

Usage:

awk -f r.awk input.file
slitvinov
  • 5,693
  • 20
  • 31
  • Thank you, it is indeed straightforward with AWK. I finally manage to do it with SED in two steps : 1. Put all comments on a new line : `sed 's/\/\//\n\/\//g'` 2. Remove ';' only on lines starting by "//" : `sed '/^\/\// s/;//g'` – Iwaa Jul 29 '16 at 12:24