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.
awk -F\# '$1!="" { print $1 ;} '
. – Archemar Sep 25 '14 at 07:02echo '#' # output a #
be handled? – Kusalananda Jun 29 '17 at 12:38echo '
. Do you have a clever way to handle those? – Questionmark Jun 29 '17 at 15:09grep -v '^#.*' filename
(Sorry, I can't submit my own answer.) (-v inverts the match, so it returns all rows that DON'T match a line starting with#
.) – Eric McLachlan Jan 29 '21 at 09:30