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

06.20.2007
| 19016 views |
  • 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
    

Comments

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

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

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

 

Where teste.sh is the script you want to strip the '#'

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

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

Snippets Manager replied on Sat, 2007/11/10 - 1: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 - 1: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 - 1:54pm

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