Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search and replace in C source code, without touching comments

Tags:

c

regex

search

I have a lot of c code in which I would like to replace old syntax style with a new style. E.g. the following prefixes "si":

int siName;

should become "i":

int iName;

But the reg-expression or other find/replace tool, should not touch any source code comments. Any solution?

like image 849
Martin Avatar asked Oct 10 '22 11:10

Martin


2 Answers

You can try out coccinelle. It has a bit of a learning curve, but it parses the C code and executes the transformations given to it in a script. For example, for renaming a function from foo to bar, the script would look like this (from here):

@@

@@

-foo()
+bar()

It can probably rename variables based on regular expressions as well, I haven't yet found out a way though.

like image 99
Antti Avatar answered Nov 01 '22 23:11

Antti


In vi use

       :%s/\<Oldword\>/Newword/gc

This asks you whether or not to replace a particular occurrence of the whole word which you may happily neglect if it is a part of the comment.

like image 39
Anerudhan Gopal Avatar answered Nov 02 '22 00:11

Anerudhan Gopal