Recursively Traverse Directory And Replace Function Calls
I would like to traverse a directory recursively and find all files that have at least one of the function calls of the following set: A(a) B(a,b) C(a,b,c) now, disregarding the a
Solution 1:
This uses os.walk to traverse all files recursively (starting from the current working directory).
The backup='_bak'
argument tells fileinput.input to make a backup of each file.
import os
import sys
import re
import fileinput
defsub_callback(match):
func,args=match.groups()
fargs=','.join('f({a})'.format(a=a) for a in args.split(','))
return ('''\
#if def LOL
{func}_new({fa})
#else
{func}({a})
#endif
'''.format(func=func,a=args,fa=fargs))
for root, dirs, files in os.walk('.'):
for line in fileinput.input(
(os.path.join(root,name) for name in files),
inplace=True,
backup='_bak'
):
line=re.sub(r'\b([A-C])\((.*?)\)',sub_callback,line)
sys.stdout.write(line)
Solution 2:
find -type f -exec perl -i.bak -pe'
if (my ($orig, $pre, $func, $args, $post) =/^((.*)\b(A|B|C)\((.*?)\)(.*?))\n/s
) {
$args= join ', ', map { "f($_)" } split /,\s*/, $args;
$_="#ifdef LOL\n";
$_.=$pre${func}_new($args)$post\n";
$_ .= "#else\n";
$_ .= $orig\n";
$_.="#endif\n";
}
' {} +
Makes a lot of assumptions. Let me know if one of them produces too many problems.
Post a Comment for "Recursively Traverse Directory And Replace Function Calls"