Delete all comments in a file using sed

后端 未结 7 1257
情书的邮戳
情书的邮戳 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 00:53

    As you have pointed out, sed won't work well if any parts of a script look like comments but actually aren't. For example, you could find a # inside a string, or the rather common $# and ${#param}.

    I wrote a shell formatter called shfmt, which has a feature to minify code. That includes removing comments, among other things:

    $ cat foo.sh
    echo $# # inline comment
    # lone comment
    echo '# this is not a comment'
    [mvdan@carbon:12] [0] [/home/mvdan]
    $ shfmt -mn foo.sh
    echo $#
    echo '# this is not a comment'
    

    The parser and printer are Go packages, so if you'd like a custom solution, it should be fairly easy to write a 20-line Go program to remove comments in the exact way that you want.

提交回复
热议问题