Shell Script – How to Remove All Comments from a File

awkgrepsedshell-scripttext processing

I have a file which includes comments:

foo
bar
stuff
#Do not show this...
morestuff
evenmorestuff#Or this

I want to print the file without including any of the comments:

foo
bar
stuff
morestuff
evenmorestuff

There are a lot of applications where this would be helpful. What is a good way to do it?

Best Answer

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.

Related Question