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.
Since there is no sample input provided by asker, I will assume a couple of cases and Bash is the input file because bash is used as the tag of the question.
Case 1: entire line is the comment
The following should be sufficient enough in most case:
sed '/^\s*#/d' file
It matches any line has which has none or at least one leading white-space characters (space, tab, or a few others, see man isspace
), followed by a #
, then delete the line by d
command.
Any lines like:
# comment started from beginning.
# any number of white-space character before
# or 'quote' in "here"
They will be deleted.
But
a="foobar in #comment"
will not be deleted, which is the desired result.
Case 2: comment after actual code
For example:
if [[ $foo == "#bar" ]]; then # comment here
The comment part can be removed by
sed "s/\s*#*[^\"']*$//" file
[^\"']
is used to prevent quoted string confusion, however, it also means that comments with quotations '
or "
will not to be removed.
Final sed
sed "/^\s*#/d;s/\s*#[^\"']*$//" file