Deepthought
Deepthought

Reputation: 2931

shell script to replace all function calls with another call

I have modified a function lets say

foo(int a, char b); into foo(int a, char b, float new_var);

The old function foo was is called from many places in the existing source code, I want to replace all occurence of foo(some_a, some_b); with foo(some_a, some_b, 0); using a script (manual editing is laborius).

I tried to do the same with grep 's/old/new/g' file but the problem is with using regex to match the parameters, and insert the same into replacement text.

PS: a & b are either valid C variable names OR valid constant values for their types.

Upvotes: 0

Views: 246

Answers (2)

fedorqui
fedorqui

Reputation: 290025

This should make it:

sed -i.bak -r "s/foo\(\s*([0-9]*)\s*,\s*(([0-Z]|'[0-Z]'))\s*\)/foo(\1, \2, 0)/g" file

Note the -i.bak stands for "replace inplace" and create a backup of the original file in file.bak.

  • foo\(\s*([0-9]*)\s*,\s*(([0-Z]|'[0-Z]'))\s*\) looks for something like foo( + spaces + digits + spaces + , + spaces + [ 'character' or character ] + spaces + ). And replaces with foo( + digits + , + character + 0 + ).

Example

$ cat a
hello foo(23, h);
this is another foo(23, bye);
this is another foo(23, 'b');
and we are calling to_foo(23, 'b'); here
foo(23, 'b'); here

$ sed -i.bak -r "s/foo\(\s*([0-9]*)\s*,\s*(([0-Z]|'[0-Z]'))\s*\)/foo(\1, \2, 0)/g" a
$ cat a
hello foo(23, h, 0);
this is another foo(23, bye);
this is another foo(23, 'b', 0);
and we are calling to_foo(23, 'b', 0); here
foo(23, 'b', 0); here

Upvotes: 1

nhahtdh
nhahtdh

Reputation: 56819

Since we are working with C code, we don't need to worry about function overloading issue.

Under the assumption of simple variable names and constant being passed into function call, and that the code was compilable before the change in function prototype:

  1. Search with foo(\([^,]*\),\([^,]*\)) and replace with foo(\1,\2,0).

    There are a few caveats, though:

    • The char field should not contain ','. It will not be replaced if it does.
    • The char field should not contain ). It will cause bad replacement.
    • There is no function whose name ends with foo. The replacement may make a mess out of your code if there is.
  2. Search with \(foo([^)]+\) and replace with \1,0 (Thanks to glenn jackman)

    There are a few caveats, though:

    • Both int and char field should not contain ). It will cause bad replacement.
    • There is no function whose name ends with foo. Similarly, the replacement may make a mess out of your code.

Upvotes: 2

Related Questions