Search code examples
perlawksedcomments

Using gawk or sed to inplace change line after or before every other match


I am trying to change the comment format for many files. Currently I have

//-----------------------------------------------------------
//   NAME : Class
//   DESCRIPTION : Vague information
//-----------------------------------------------------------

The number of - may be different with each file, or even with each case. I would like something like this to keep readability with the rest of the code while still allowing compatibility with a documenting program:

//-----------------------------------------------------------
/*!
//   NAME : Class
//   DESCRIPTION : Vague information
*/
//-----------------------------------------------------------

But this is also acceptable, and for sure easier:

/*!
//   NAME : Class
//   DESCRIPTION : Vague information
*/

For a start, I have tried something like

$ gawk -i inplace '/^\/\/--.*/&&v++%2 {sub(/^\/\/--.*, "\/\*!")}' filename.cpp and then $ gawk -i inplace '/^\/\/--.*/{sub(/^\/\/--.*, "\*\/")}' filename.cpp

which obviously has some syntax errors; the goal was to change every odd instance of //---* with /*!, and then replacing //---* with */, and for just one file, instead of many .cpp and .h/.hpp files.


Solution

  • Given:

    $ cat file
    //-----------------------------------------------------------
    //   NAME : Class
    //   DESCRIPTION : Vague information
    //-----------------------------------------------------------
    

    With THIS regex, you can use perl:

    $ perl -0777 -pE 's/^(\/\/-+\R)(\/\/[\s\S]*?)(^\/\/-+\R?)/\1\/\*!\n\2\*\/\n\3/gm' file 
    //-----------------------------------------------------------
    /*!
    //   NAME : Class
    //   DESCRIPTION : Vague information
    */
    //-----------------------------------------------------------
    

    Perl also has an inplace option.