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

Leave a Reply