A fun regular expression for the day. change all function calls to another.
Posted by peeterjoot on December 18, 2009
Hit some nasty old school code today that dates back to our one-time 16-bit OS/2 port. I figured out that 730 lines of code for an ancient function called sqlepost() could all be removed if I could make a change of all lines like so:
- sqlepost(SQLT_SQLE, SQLT_SQLE_SUBCOORD_TERM, 122, SQLE_EBAD_DB_ERR, sizeof(eRC), &eRC); + pdLog( PD_DEV, SQLT_SQLE_SUBCOORD_TERM, eRC, 122, PD_LEVEL_SEV, 0 ) ;
(83 places). A desirable side effect of making this change is that we will stop logging the return code as a byte reversed hex number, and instead log it as a return code. Easier on developers and system testers alike.
perl -p is once again a good friend for this sort of task
s/sqlepost\s*\( \s*(.*?)\s*, # componentID -- unused. \s*(.*?)\s*, # functionID \s*(.*?)\s*, # probe \s*(.*?)\s*, # index -- unused. \s*(.*?)\s*, # size -- unused. \s*&(.*?)\s*\)\s*; # rc /pdLog( PD_DEV, $2, $6, $3, PD_LEVEL_SEV, 0 ) ;/x ;
I made a quick manual modification of each of the call sites that weren’t all in one line, with control-J in vim to put the whole function call on one line, then just had to run:
perl -p -i ./replacementScript `cat listOfFilesWithTheseCalls`
Voila! Very nice if I have to say so myself;)
EDIT: it was pointed out to me that the regular expressions used above are not entirely obvious. Here’s a quick synopsis:
\s space . any character * zero or more of the preceding (.*) capture an expression (creates $1, $2, ...) ie. zero or more of anything. (.*?) capture an expression, but don't be greedy, only capturing the minimal amount. \( a plain old start brace character (ie. non-capturing) \) a plain old end brace character.