Removing c-style comments with sedHow to delete empty comments with sed?Deleting all C comments with sedHow...

Why do I have multiple (unassociated) temporal history tables?

How to acknowledge an embarrassing job interview, now that I work directly with the interviewer?

It took me a lot of time to make this, pls like. (YouTube Comments #1)

Why don't American passenger airlines operate dedicated cargo flights any more?

Quenching swords in dragon blood; why?

Are there neural networks with very few nodes that decently solve non-trivial problems?

Dilemma of explaining to interviewer that he is the reason for declining second interview

Lick explanation

What to do when being responsible for data protection in your lab, yet advice is ignored?

Explain the objections to these measures against human trafficking

Is there any differences between "Gucken" and "Schauen"?

Would a National Army of mercenaries be a feasible idea?

Word or phrase for showing great skill at something without formal training in it

Why does lambda auto& parameter choose const overload?

Would these multi-classing house rules cause unintended problems?

Book where aliens are selecting humans for food consumption

If I delete my router's history can my ISP still provide it to my parents?

Can a dragon be stuck looking like a human?

"Free" Hopf algebra

Are there any modern advantages of a fire piston?

What is the most triangles you can make from a capital "H" and 3 straight lines?

What is the in-universe cost of a TIE fighter?

Why does String.replaceAll() work differently in Java 8 from Java 9?

Solubility of a tribasic weak acid



Removing c-style comments with sed


How to delete empty comments with sed?Deleting all C comments with sedHow to remove multiple blank lines from a file?how to select specific range of line & count the specific occurence of the first charcter w.r.t. each unique second charcter?convert C style comments to C++ style using sedSed command that would ignore any commented matchsed stripping comments inlineWhat is the benefit of /etc/apt/sources.list.d over /etc/apt/sources.listsed command removing #Removing characters with sed













1















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.










share|improve this question









New contributor




forteller is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





















  • @jimmij, the OP doesn't want to remove all comments, only // characteristic_comment_to_delete

    – Stéphane Chazelas
    3 hours ago











  • For C-style comments, How can I delete all characters falling under /* .... */ including /* & */? would be a closer match.

    – Stéphane Chazelas
    3 hours ago











  • Off topic, but you're not really running this command as root, are you? That # prompt makes my eye twitch.

    – David Conrad
    12 mins ago
















1















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.










share|improve this question









New contributor




forteller is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





















  • @jimmij, the OP doesn't want to remove all comments, only // characteristic_comment_to_delete

    – Stéphane Chazelas
    3 hours ago











  • For C-style comments, How can I delete all characters falling under /* .... */ including /* & */? would be a closer match.

    – Stéphane Chazelas
    3 hours ago











  • Off topic, but you're not really running this command as root, are you? That # prompt makes my eye twitch.

    – David Conrad
    12 mins ago














1












1








1








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.










share|improve this question









New contributor




forteller is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












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.







linux sed






share|improve this question









New contributor




forteller is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




forteller is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 1 hour ago









Rui F Ribeiro

40.7k1479137




40.7k1479137






New contributor




forteller is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 5 hours ago









fortellerforteller

62




62




New contributor




forteller is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





forteller is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






forteller is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.













  • @jimmij, the OP doesn't want to remove all comments, only // characteristic_comment_to_delete

    – Stéphane Chazelas
    3 hours ago











  • For C-style comments, How can I delete all characters falling under /* .... */ including /* & */? would be a closer match.

    – Stéphane Chazelas
    3 hours ago











  • Off topic, but you're not really running this command as root, are you? That # prompt makes my eye twitch.

    – David Conrad
    12 mins ago



















  • @jimmij, the OP doesn't want to remove all comments, only // characteristic_comment_to_delete

    – Stéphane Chazelas
    3 hours ago











  • For C-style comments, How can I delete all characters falling under /* .... */ including /* & */? would be a closer match.

    – Stéphane Chazelas
    3 hours ago











  • Off topic, but you're not really running this command as root, are you? That # prompt makes my eye twitch.

    – David Conrad
    12 mins ago

















@jimmij, the OP doesn't want to remove all comments, only // characteristic_comment_to_delete

– Stéphane Chazelas
3 hours ago





@jimmij, the OP doesn't want to remove all comments, only // characteristic_comment_to_delete

– Stéphane Chazelas
3 hours ago













For C-style comments, How can I delete all characters falling under /* .... */ including /* & */? would be a closer match.

– Stéphane Chazelas
3 hours ago





For C-style comments, How can I delete all characters falling under /* .... */ including /* & */? would be a closer match.

– Stéphane Chazelas
3 hours ago













Off topic, but you're not really running this command as root, are you? That # prompt makes my eye twitch.

– David Conrad
12 mins ago





Off topic, but you're not really running this command as root, are you? That # prompt makes my eye twitch.

– David Conrad
12 mins ago










4 Answers
4






active

oldest

votes


















3














Sed has a d command for deleting whole lines - it can also take an arbitrary (non /) delimiter, however it needs to be escaped with on first use. So you could do something like



$ sed -e '#^// characteristic_comment_to_delete$#d' -e 's#// characteristic_comment_to_delete.*##' file
some_code
some_more_code // another_comment
another_line_with_code
even_more_code


to first delete lines that consist entirely of // characteristic_comment_to_delete, then substitute any remaining occurrences.



(I changed your & to # to avoid confusion with the sed & replacement operator).






share|improve this answer































    1














    With GNU sed:



    sed 's|s*// characteristic_comment_to_delete.*||;T;/./!d'


    T is a GNU extension that branches off unless the previous s substitution was successful. So if no comment was removed, we branch off, and the next /./!d (which deletes the line unless it contains at least one character) is skipped.



    Standard equivalent:



    sed '/[[:space:]]*// characteristic_comment_to_delete.*/{s///;/./!d;}'


    Or:



    sed 's|[[:space:]]*// characteristic_comment_to_delete.*||
    t 1
    b
    :1
    /./!d'


    Both suppress empty lines only if the substitution was successful.






    share|improve this answer

































      0














      If you accept an AWK solution:



      awk -F "[   ]*//[   ]*characteristic_comment_to_delete.*" '$1 != "" { print $1; }' some_file.cpp


      Note: The pattern contains a space and a TAB between the brackets [ ].



      This solution does not correctly handle string literals containing the comment pattern, e.g.
      char text[] = "// characteristic_comment_to_delete bla bla";






      share|improve this answer































        0














        Demonstrating storing the comment in a shell variable, and escaping the slash characters with shell parameter expansion. Otherwise, same as steeldriver's answer.



        $ comment='// characteristic_comment_to_delete'
        $ sed -e "/^[[:blank:]]*${comment////\/}/d" -e "s/${comment////\/}.*//" file
        some_code
        some_more_code // another_comment
        another_line_with_code
        even_more_code





        share|improve this answer























          Your Answer








          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "106"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });






          forteller is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f503784%2fremoving-c-style-comments-with-sed%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          4 Answers
          4






          active

          oldest

          votes








          4 Answers
          4






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          3














          Sed has a d command for deleting whole lines - it can also take an arbitrary (non /) delimiter, however it needs to be escaped with on first use. So you could do something like



          $ sed -e '#^// characteristic_comment_to_delete$#d' -e 's#// characteristic_comment_to_delete.*##' file
          some_code
          some_more_code // another_comment
          another_line_with_code
          even_more_code


          to first delete lines that consist entirely of // characteristic_comment_to_delete, then substitute any remaining occurrences.



          (I changed your & to # to avoid confusion with the sed & replacement operator).






          share|improve this answer




























            3














            Sed has a d command for deleting whole lines - it can also take an arbitrary (non /) delimiter, however it needs to be escaped with on first use. So you could do something like



            $ sed -e '#^// characteristic_comment_to_delete$#d' -e 's#// characteristic_comment_to_delete.*##' file
            some_code
            some_more_code // another_comment
            another_line_with_code
            even_more_code


            to first delete lines that consist entirely of // characteristic_comment_to_delete, then substitute any remaining occurrences.



            (I changed your & to # to avoid confusion with the sed & replacement operator).






            share|improve this answer


























              3












              3








              3







              Sed has a d command for deleting whole lines - it can also take an arbitrary (non /) delimiter, however it needs to be escaped with on first use. So you could do something like



              $ sed -e '#^// characteristic_comment_to_delete$#d' -e 's#// characteristic_comment_to_delete.*##' file
              some_code
              some_more_code // another_comment
              another_line_with_code
              even_more_code


              to first delete lines that consist entirely of // characteristic_comment_to_delete, then substitute any remaining occurrences.



              (I changed your & to # to avoid confusion with the sed & replacement operator).






              share|improve this answer













              Sed has a d command for deleting whole lines - it can also take an arbitrary (non /) delimiter, however it needs to be escaped with on first use. So you could do something like



              $ sed -e '#^// characteristic_comment_to_delete$#d' -e 's#// characteristic_comment_to_delete.*##' file
              some_code
              some_more_code // another_comment
              another_line_with_code
              even_more_code


              to first delete lines that consist entirely of // characteristic_comment_to_delete, then substitute any remaining occurrences.



              (I changed your & to # to avoid confusion with the sed & replacement operator).







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered 5 hours ago









              steeldriversteeldriver

              36.4k35286




              36.4k35286

























                  1














                  With GNU sed:



                  sed 's|s*// characteristic_comment_to_delete.*||;T;/./!d'


                  T is a GNU extension that branches off unless the previous s substitution was successful. So if no comment was removed, we branch off, and the next /./!d (which deletes the line unless it contains at least one character) is skipped.



                  Standard equivalent:



                  sed '/[[:space:]]*// characteristic_comment_to_delete.*/{s///;/./!d;}'


                  Or:



                  sed 's|[[:space:]]*// characteristic_comment_to_delete.*||
                  t 1
                  b
                  :1
                  /./!d'


                  Both suppress empty lines only if the substitution was successful.






                  share|improve this answer






























                    1














                    With GNU sed:



                    sed 's|s*// characteristic_comment_to_delete.*||;T;/./!d'


                    T is a GNU extension that branches off unless the previous s substitution was successful. So if no comment was removed, we branch off, and the next /./!d (which deletes the line unless it contains at least one character) is skipped.



                    Standard equivalent:



                    sed '/[[:space:]]*// characteristic_comment_to_delete.*/{s///;/./!d;}'


                    Or:



                    sed 's|[[:space:]]*// characteristic_comment_to_delete.*||
                    t 1
                    b
                    :1
                    /./!d'


                    Both suppress empty lines only if the substitution was successful.






                    share|improve this answer




























                      1












                      1








                      1







                      With GNU sed:



                      sed 's|s*// characteristic_comment_to_delete.*||;T;/./!d'


                      T is a GNU extension that branches off unless the previous s substitution was successful. So if no comment was removed, we branch off, and the next /./!d (which deletes the line unless it contains at least one character) is skipped.



                      Standard equivalent:



                      sed '/[[:space:]]*// characteristic_comment_to_delete.*/{s///;/./!d;}'


                      Or:



                      sed 's|[[:space:]]*// characteristic_comment_to_delete.*||
                      t 1
                      b
                      :1
                      /./!d'


                      Both suppress empty lines only if the substitution was successful.






                      share|improve this answer















                      With GNU sed:



                      sed 's|s*// characteristic_comment_to_delete.*||;T;/./!d'


                      T is a GNU extension that branches off unless the previous s substitution was successful. So if no comment was removed, we branch off, and the next /./!d (which deletes the line unless it contains at least one character) is skipped.



                      Standard equivalent:



                      sed '/[[:space:]]*// characteristic_comment_to_delete.*/{s///;/./!d;}'


                      Or:



                      sed 's|[[:space:]]*// characteristic_comment_to_delete.*||
                      t 1
                      b
                      :1
                      /./!d'


                      Both suppress empty lines only if the substitution was successful.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited 13 mins ago

























                      answered 3 hours ago









                      Stéphane ChazelasStéphane Chazelas

                      308k57581939




                      308k57581939























                          0














                          If you accept an AWK solution:



                          awk -F "[   ]*//[   ]*characteristic_comment_to_delete.*" '$1 != "" { print $1; }' some_file.cpp


                          Note: The pattern contains a space and a TAB between the brackets [ ].



                          This solution does not correctly handle string literals containing the comment pattern, e.g.
                          char text[] = "// characteristic_comment_to_delete bla bla";






                          share|improve this answer




























                            0














                            If you accept an AWK solution:



                            awk -F "[   ]*//[   ]*characteristic_comment_to_delete.*" '$1 != "" { print $1; }' some_file.cpp


                            Note: The pattern contains a space and a TAB between the brackets [ ].



                            This solution does not correctly handle string literals containing the comment pattern, e.g.
                            char text[] = "// characteristic_comment_to_delete bla bla";






                            share|improve this answer


























                              0












                              0








                              0







                              If you accept an AWK solution:



                              awk -F "[   ]*//[   ]*characteristic_comment_to_delete.*" '$1 != "" { print $1; }' some_file.cpp


                              Note: The pattern contains a space and a TAB between the brackets [ ].



                              This solution does not correctly handle string literals containing the comment pattern, e.g.
                              char text[] = "// characteristic_comment_to_delete bla bla";






                              share|improve this answer













                              If you accept an AWK solution:



                              awk -F "[   ]*//[   ]*characteristic_comment_to_delete.*" '$1 != "" { print $1; }' some_file.cpp


                              Note: The pattern contains a space and a TAB between the brackets [ ].



                              This solution does not correctly handle string literals containing the comment pattern, e.g.
                              char text[] = "// characteristic_comment_to_delete bla bla";







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered 4 hours ago









                              BodoBodo

                              1,770212




                              1,770212























                                  0














                                  Demonstrating storing the comment in a shell variable, and escaping the slash characters with shell parameter expansion. Otherwise, same as steeldriver's answer.



                                  $ comment='// characteristic_comment_to_delete'
                                  $ sed -e "/^[[:blank:]]*${comment////\/}/d" -e "s/${comment////\/}.*//" file
                                  some_code
                                  some_more_code // another_comment
                                  another_line_with_code
                                  even_more_code





                                  share|improve this answer




























                                    0














                                    Demonstrating storing the comment in a shell variable, and escaping the slash characters with shell parameter expansion. Otherwise, same as steeldriver's answer.



                                    $ comment='// characteristic_comment_to_delete'
                                    $ sed -e "/^[[:blank:]]*${comment////\/}/d" -e "s/${comment////\/}.*//" file
                                    some_code
                                    some_more_code // another_comment
                                    another_line_with_code
                                    even_more_code





                                    share|improve this answer


























                                      0












                                      0








                                      0







                                      Demonstrating storing the comment in a shell variable, and escaping the slash characters with shell parameter expansion. Otherwise, same as steeldriver's answer.



                                      $ comment='// characteristic_comment_to_delete'
                                      $ sed -e "/^[[:blank:]]*${comment////\/}/d" -e "s/${comment////\/}.*//" file
                                      some_code
                                      some_more_code // another_comment
                                      another_line_with_code
                                      even_more_code





                                      share|improve this answer













                                      Demonstrating storing the comment in a shell variable, and escaping the slash characters with shell parameter expansion. Otherwise, same as steeldriver's answer.



                                      $ comment='// characteristic_comment_to_delete'
                                      $ sed -e "/^[[:blank:]]*${comment////\/}/d" -e "s/${comment////\/}.*//" file
                                      some_code
                                      some_more_code // another_comment
                                      another_line_with_code
                                      even_more_code






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered 1 hour ago









                                      glenn jackmanglenn jackman

                                      52k572112




                                      52k572112






















                                          forteller is a new contributor. Be nice, and check out our Code of Conduct.










                                          draft saved

                                          draft discarded


















                                          forteller is a new contributor. Be nice, and check out our Code of Conduct.













                                          forteller is a new contributor. Be nice, and check out our Code of Conduct.












                                          forteller is a new contributor. Be nice, and check out our Code of Conduct.
















                                          Thanks for contributing an answer to Unix & Linux Stack Exchange!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f503784%2fremoving-c-style-comments-with-sed%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Benedict Cumberbatch Contingut Inicis Debut professional Premis Filmografia bàsica Premis i...

                                          Monticle de plataforma Contingut Est de Nord Amèrica Interpretacions Altres cultures Vegeu...

                                          Escacs Janus Enllaços externs Menú de navegacióEscacs JanusJanusschachBrainKing.comChessV