使用脚本从函数中提取参数

时间:2010-07-27 09:07:31

标签: linux bash scripting sed

我有一个包含这样的函数原型的文件:

int func1(type1 arg, int x);

type2 funct2(int z, char* buffer);

我想创建一个将打印

的脚本(bash,sed,awk等)
function = func1 // first argument type = type1// second argument type = int
function = func1 // first argument type = int// second argument type = char*

换句话说,标记每一行并打印函数名称和参数。另外,我想将这些标记作为变量保存,以便稍后打印,例如echo $4

2 个答案:

答案 0 :(得分:1)

另一种方法是使用“-g”进行编译并读取调试信息 This answer可以帮助您阅读调试信息并找出函数参数(它是Python,而不是bash,但我建议使用Python或Perl而不是bash)。

最终的解决方案比基于文本解析的任何解决方案都强大得多。它将处理可以定义函数的所有不同方式,甚至可以处理宏中定义的函数之类的疯狂事物。

为了让您更好地说服您(或者如果您不相信,请帮助您做到正确),这里有一个可能会破坏您的解析的测试用例列表:

// Many lines
const
char
*

f
(
int
x
)
{
}

// Count parenthesis!
void f(void (*f)(void *f)) {}

// Old style
void f(a, b)
int a;
char *b
{
}

// Not a function
int f=sizeof(int);

// Nesting
int f() {
    int g() { return 1; }
    return g();
}

// Just one
void f(int x /*, int y */) { }

// what if?
void (int x
#ifdef ALSO_Y
     , int y
#endif
) { }

// A function called __attribute__?
static int __attribute__((always_inline)) f(int x) {}

答案 1 :(得分:0)

这是一个开始。

#!/bin/bash
#bash 3.2+
while read -r line
do
  line="${line#* }"
  [[ $line =~ "^(.*)\((.*)\)" ]]
  echo  "function: ${BASH_REMATCH[1]}"
  echo  "args: ${BASH_REMATCH[2]}"
  ARGS=${BASH_REMATCH[2]}
  FUNCTION=${BASH_REMATCH[1]}
  # break down the arguments further.
  set -- $ARGS
  echo "first arg type:$1 , second arg type: $2"
done <"file"

输出

$ ./shell.sh
function: func1
args: type1 arg, int x
first arg type:type1 , second arg type: arg,
function: funct2
args: int z, char* buffer
first arg type:int , second arg type: z,