Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
2  
with perl: perl -ple 's;/\*.*?\*/;;g' –  Prince John Wesley Jun 28 '12 at 17:24

2 Answers 2

up vote 3 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

 
discard

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.