Delete all comments in a file using sed

后端 未结 7 1264
情书的邮戳
情书的邮戳 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

    To remove comment lines (lines whose first non-whitespace character is #) but not shebang lines (lines whose first characters are #!):

    sed '/^[[:space:]]*#[^!]/d; /#$/d' file
    

    The first argument to sed is a string containing a sed program consisting of two delete-line commands of the form /regex/d. Commands are separated by ;. The first command deletes comment lines but not shebang lines. The second command deletes any remaining empty comment lines. It does not handle trailing comments.

    The last argument to sed is a file to use as input. In Bash, you can also operate on a string variable like this:

    sed '/^[[:space:]]*#[^!]/d; /#$/d' <<< "${MYSTRING}"
    

    Example:

    # test.sh
    S0=$(cat << HERE
    #!/usr/bin/env bash
    # comment
      # indented comment
    echo 'FOO' # trailing comment
    # last line is an empty, indented comment
      #
    HERE
    )
    printf "\nBEFORE removal:\n\n${S0}\n\n"
    S1=$(sed '/^[[:space:]]*#[^!]/d; /#$/d' <<< "${S0}")
    printf "\nAFTER removal:\n\n${S1}\n\n"
    

    Output:

    $ bash test.sh
    
    BEFORE removal:
    
    #!/usr/bin/env bash
    # comment
      # indented comment
    echo 'FOO' # trailing comment
    # last line is an empty, indented comment
      #    
    
    
    AFTER removal:
    
    #!/usr/bin/env bash
    echo 'FOO' # trailing comment
    

提交回复
热议问题