RegEx for replacing C++ single line comments with C Style comments

This is a very simple but usefull regular expression. Some compilers have problems with C++ comments like // comment. In ANSI C you writing comments like /* comment */. This can be a pain to replace manually.

But with regular expressions it’s easy. Vim example:

:%s#//\(.*\)#/*\1 */#

RegEx explained: Normally you are usig substitutions like s/pattern/replace/. The slash is the common delimiter, but you can also use the hash sign # so you don’t have to escape the slash characters in the pattern (e.g. s#pattern#replace#)

If you have to do this for multiple files you can of course also use find and sed for that job.

find . -name "*.h" -exec ./replace.sh {} \;

where replace.sh is a little shell script so that it is easier to write the sed expression.

replace.sh:

#!/bin/bash
cat $1 | sed -e ‘s#//\(.*\)#/*\1 */#’ > $1.tmp
mv $1.tmp $1

Update: It’s even easier to use in-place replacement functionlity of sed:

find . -name "*.h" -exec sed -i 's#//\(.*\)#/*\1 */#' {} \;

Advertisements

2 Responses to “RegEx for replacing C++ single line comments with C Style comments”


  1. 1 elpulpo November 17, 2010 at 1:27 pm

    better do this
    find . -iname “*.h” -exec sed -i ‘s#//\(.*\)#/*\1 */#’ {} \;


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s





%d bloggers like this: