Linux script that counts number of printf parameters for each occurrence

眉间皱痕 提交于 2019-12-13 06:01:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!