问题
I want to write a script in sh that for each given file, for each printf occurrence, it will count the number of %'s (or alternatively the number of parameters the printf function receives) and rename the printf to printfX, when X is that number.
I got stuck because printf doesn't end with new line...
e.g.
printf("hello "
"world %d\n", 1);
should return
printf1("hello "
"world %d\n", 1);
回答1:
There is no simple (= as in script) solution for this because to parse C code, you need an LL(1) parser.
But you can format all the code in the same way so your script can handle the different cases. So what you should do first is find all lines with printf but without );:
grep "printf" ...files... | grep -v ");"
Then fix these files until you don't get any output any more.
回答2:
As a starting point, a simple Perl script to calculate the number of % characters in double quotes before a comma or closing paren.
perl -0777pe 's/printf\s*\(\s*\"((?:[^"]*\"\s*\")*[^"]*)\"\s*([,)]\s*)/
my ($f, $c, $t) = ($1, $1, $2);
sprintf("printf%i(\"%s\"%s", ($c =~ tr-%--), $f, $t) /ges' files ...
This will substitute inside quoted strings, comments, etc; it will catch fprintf and sprintf and myownsacredprintf as well as plain printf.
来源:https://stackoverflow.com/questions/11886392/linux-script-that-counts-number-of-printf-parameters-for-each-occurrence