Delete all comments in a file using sed

后端 未结 7 1247
情书的邮戳
情书的邮戳 2020-12-17 00:14

How would you delete all comments using sed from a file(defined with #) with respect to \'#\' being in a string?

This helped out a lot except for the string portion.

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-17 01:10

    Since there is no sample input provided by asker, I will assume a couple of cases and Bash is the input file because bash is used as the tag of the question.

    Case 1: entire line is the comment

    The following should be sufficient enough in most case:

    sed '/^\s*#/d' file
    

    It matches any line has which has none or at least one leading white-space characters (space, tab, or a few others, see man isspace), followed by a #, then delete the line by d command.

    Any lines like:

    # comment started from beginning.
             # any number of white-space character before
        # or 'quote' in "here"
    

    They will be deleted.

    But

    a="foobar in #comment"
    

    will not be deleted, which is the desired result.

    Case 2: comment after actual code

    For example:

    if [[ $foo == "#bar" ]]; then # comment here
    

    The comment part can be removed by

    sed "s/\s*#*[^\"']*$//" file
    

    [^\"'] is used to prevent quoted string confusion, however, it also means that comments with quotations ' or " will not to be removed.

    Final sed

    sed "/^\s*#/d;s/\s*#[^\"']*$//" file
    

提交回复
热议问题