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
Advertisements

Comment whole section from ini file

Instead of using the ansible ini_file state=absent section=”Zabbix”, you can use this instead, to comment out the section. I realize you can just do a backup=yes option, but for the quick cases where you don’t want to fire up ansible:

tmpfile1=$( mktemp ); sed -r -e '/^\[/i#ENGLISH877' ~/foo | sed -r -e '/^\[Zabbix\]/,/ENGLISH877/s/^/#/;' | sed -r -e '/#ENGLISH877/d' > ${tmpfile1}; cat ${tmpfile1} > ~/foo

Explanation

The first sed statement inserts a new line with content “#ENGLISH877” (random string that will be unlikely to cause collisions) right before the start of each new section.
The second sed statement then modifies the section specified (“Zabbix”) and inserts comments at the beginning.
The last sed removes all instances of the random string we inserted.

Hide comments and blank lines in file

Hide comments and blank lines when viewing file

Original title: Show all non-blank non-comment lines in file

If you want to see just the lines with content, such as in a config file, use this one-liner:

grep -viE '^\s*((#|;).*)?$' smb.conf

How it works

grep -v means invert the selection, i.e., everything that does not match this search.
-iE case Insensitive, and treat this as a regular Expression. Technically there are no letters being searched, so the i is irrelevant, but I always use it in my searches anyway.
^ start of line
\s* white space, any amount from zero onward. This is a greedy search, so it will match all the white space (spaces, tabs, etc.)
(#|;) either a pound or a semicolon, which usually denote comments in config files (in my case, smb.conf)
((#|;).*) the above sentence, followed by any character (the period), and any amount of those “any characters.”
((#|;).*)? the whole thing in parentheses shown here, optionally.
$ end of line
So any line that starts with any amount of white space, followed by (a comment symbol, followed by anything else) optionally, and the end of the line.
So show everything but the above sentence, and tada, just the important stuff.