2010-07-27 42 views
0

我有這樣與函數原型文件:提取參數與腳本

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

回答

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, 
+0

我怎麼可以存儲在sed的索引嗎?例如 echo「abcd」| sed's/ab \(。* \)/ \ 1 /' 這會打印「cd」。我如何將cd存儲在變量中? – cateof 2010-07-27 09:45:48

+0

'var = $(echo「abcd」| sed's/ab(。*)/ \ 1 /')' – ghostdog74 2010-07-27 09:51:35

+0

幾乎在那裏。我有行「int func(struct type1 * tp,TYPE1 * name,TYPE2 * name2);」。我想存儲一個變量TYPE1和TYPE2並稍後打印它們 – cateof 2010-07-27 10:13:48

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) {}