Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

Remove comments from file but preserve strings

Remove comments from file but preserve strings containing the comment symbol

sed '/#/!b;s/^/\n/;ta;:a;s/\n$//;t;s/\n\(\("[^"]*"\)\|\('\''[^'\'']*'\''\)\)/\1\n/;ta;s/\n\([^#]\)/\1\n/;ta;s/\n.*//' file

Explanation

/#/!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.

References

  1. Shamelessly plagiarized from http://stackoverflow.com/a/13551154/3569534

Comments