DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Remove Comments From A File

  • submit to reddit
        Remove all comment lines from a file.

sed -e '/^#/d' $1 | more
or to output it to a new file
sed -e '/^#/d' $1 > $1.nocomments


Joao Limberger replied on Fri, 2012/10/26 - 2:01pm

To delete just the '#' and keep the sha-bang... you can try this:

awk '{ if( ($0 !~ /^ *#/) || ($0 ~ /^ *#!/) ) print $0 ; else  {gsub(/^ *#/ , "" ); print } } ' 


Where is the script you want to strip the '#'

Snippets Manager replied on Mon, 2009/03/23 - 5:44am

I like to use: grep -E "^[[:blank:]]*#" to read all comments (but inlines).

Snippets Manager replied on Sat, 2007/11/10 - 12:43am

Ok - i fixed it with the help of the super cool guys in the #bash irc channel, so i'll post it here for anyone who needs it. sed '1p; /^[[:blank:]]*#/d; s/[[:blank:]][[:blank:]]*#.*//' - this will leave the shebang line alone, and will delete all comments except for the inline ones (too risky - it could delete any '#' symbols used in the script itself)

Snippets Manager replied on Sat, 2007/11/10 - 12:43am

Thanks for posting that - theres a problem though - it wont remove comments that are indented, i.e. there are spaces between the comment symbol # and the left hand margin. it also doesnt work if the comment is on the same line behind a command.

Snippets Manager replied on Thu, 2007/06/21 - 12:54pm

Changing that to sed -e '/^#[^!]/d' | less would prevent the shebang line from getting removed.