How can I remove all comments from a file?
One way to remove all comments is to use grep
with -o
option:
grep -o '^[^#]*' file
where
-o
: prints only matched part of the line- first
^
: beginning of the line [^#]*
: any character except#
repeated zero or more times
Note that empty lines will be removed too, but lines with only spaces will stay.
I believe sed
can do a much better job of this than grep
. Something like this:
sed '/^[[:blank:]]*#/d;s/#.*//' your_file
Explanation
sed
will by default look at your file line by line and print each line after possibly applying the transformations in the quotes. (sed '' your_file
will just print all the lines unchanged).- Here we're giving
sed
two commands to perform on each line (they're separated by a semicolon). - The first command says:
/^[[:blank:]]*#/d
. In English, that means if the line matches a hash at its beginning (preceded by any number of leading blanks), delete that line (it will not be printed). - The second command is:
s/#.*//
. In English that is, substitute a hash mark followed by as many things as you can find (till the end of the line, that is) with nothing (nothing is the empty space between the final two//
). - In summary, this will run through your file deleting lines that consist entirely of comments and any lines left after that will have the comments stricken out of them.
As others have pointed out, sed and other text-based tools 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.