Delete all comments in a file using sed

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

    This might work for you (GNU sed):

    sed '/#/!b;s/^/\n/;ta;:a;s/\n$//;t;s/\n\(\("[^"]*"\)\|\('\''[^'\'']*'\''\)\)/\1\n/;ta;s/\n\([^#]\)/\1\n/;ta;s/\n.*//' file
    
    • /#/!b if the line does not contain a # bail out
    • s/^/\n/ insert a unique marker (\n)
    • ta;:a jump to a loop label (resets the substitute true/false flag)
    • s/\n$//;t if marker at the end of the line, remove and bail out
    • s/\n\(\("[^"]*"\)\|\('\''[^'\'']*'\''\)\)/\1\n/;ta if the string following the marker is a quoted one, bump the marker forward of it and loop.
    • s/\n\([^#]\)/\1\n/;ta if the character following the marker is not a #, bump the marker forward of it and loop.
    • s/\n.*// the remainder of the line is comment, remove the marker and the rest of line.

提交回复
热议问题