Is there a command line tool that can remove comments from an XML file? Or do I need to write a small program that makes use of an XML parser to do this?

Update: I'm not interested in solutions that only handle a subset of all possible XML files.

For instance a regexp can't handle XML parsing.



I would do it in this way:

cat myfile.xml | sed '/<!--.*-->/d' | sed '/<!--/,/-->/d' > cleaned.xml


awk 'in_comment&&/-->/{sub(/([^-]|-[^-])*--+>/,"");in_comment=0}


xmlstarlet ed -d '//comment()' file.xml
  • I know regex solutions can't handle XML parsing (without possible errors). But I guess the third solution is using a real XML parser under the hood? – Erik Sjölund Sep 19 '14 at 11:07
  • Erik, yes, xmlstarlet is designed for xml manipulation. – Frantique Sep 19 '14 at 11:26
  • Ok, I checked. xmlstarlet uses libxml2. If you remove the first sed and awk suggestions that are not correct according to me, I'll accept the xmlstarlet suggestion as the accepted answer. – Erik Sjölund Sep 19 '14 at 12:04
  • it's disappointing to know that none of the big editors (Sublime, vim, Atom, Notepad++) have this feature built-in. Sad, sad, sad. Thanks @Frantique – Lucas Pottersky Jun 28 '16 at 18:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.