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 #.

  • 2
    with perl: perl -ple 's;/\*.*?\*/;;g' Commented Jun 28, 2012 at 17:24

2 Answers 2


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"
  • 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
    Commented Jun 29, 2012 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@/\*[^*]*\*/@@;'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .