Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a text file that contains many rows of this sort of thing:

/*[17:51:27][1 ms]*/ UPDATE `country` SET `region_id` = '4' WHERE `country_id` = '36'; 

Is there a way that I can use sed to remove the comments only , so that's everything that starts with a /* and ends with a */? This would make the line become:

UPDATE `country` SET `region_id` = '4' WHERE `country_id` = '36';

I know how to use sed to remove an entire line that starts with something, in the example of a text file with SQL in it it would likely be a hash symbol #.

share|improve this question
with perl: perl -ple 's;/\*.*?\*/;;g' – Prince John Wesley Jun 28 '12 at 17:24
up vote 4 down vote accepted

Because sed matches in a greedy manner, there is always the possibility that text past the end of the comment will be matched instead of the preceding real end-of-comment marker, eg. as in a quoted string which contains "*/".
This cannot be handled by sed in a simple manner, but you can work around it. Here is one such method: using single-character placeholder for the two-character end delimiter. Using hex value \x01 as the stand-in characters is safe (ie. won't clash with existing text), as it does not exist in normal text.

sed "\|^/\*.*\*/|{ s|\*/|\x01|; s|.*\x01|| }" "$file"

perl, on the other hand, can optionally handle lazy matching (and a lot more). As already mentioned by Prince John Wesley in the comments, here is the lazy perl equivalent.

perl -ple 's|/\*.*?\*/||g' "$file"
share|improve this answer
The perl example worked, many thanks. Using Perl and writing the output to a new file I done this: perl -ple 's|/\*.*?\*/||g' "txt/crmpicco.txt" > text/new_crmpicco.txt – crmpicco Jun 29 '12 at 8:24

Try this one:

sed 's@/\*[^/]*\*/@@'

Unfortunately it may has difficulties with comments with / inside.

May be it will be useful two variants together: to be sure that absolutely all comments are removed:

sed 's@/\*[^/]*\*/@@;s@/\*[^*]*\*/@@;'
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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