2014-08-29 152 views
0

我試圖使用find + SED/AWK替換此字符串:查找並用sed/awk替換多行?

main(argc, argv) 
int argc; 
char *argv[]; 
{ 

有:

int main(int argc, char *argv[]) 
{ 

有誰知道如何做到這一點?

非常感謝!

+0

您是否只想在sed中使用該解決方案? – 2014-08-29 12:49:45

+0

如果可能的話 - 我可以使用find + sed來替換大量的文件。 – James 2014-08-29 12:50:33

+0

如果你在'awk'中得到了一個解決方案,你是否也可以使用'find + awk'? – Barmar 2014-08-29 12:51:45

回答

1
cat test.txt 
    main(argc, argv) 
    int argc; 
    char *argv[]; 
    { 

這個awk中它產生所需的輸出:

cat test.txt | awk 'BEGIN { args=""; nb=0; }; /main\(argc, argv\)/,/\{/ { if (!/^(main|\{).*$/) { tmp=$0; sub(/;/,"",tmp); if (nb) { args=(args "," tmp); nb+=1; } else { args=tmp; nb+=1;} };} END { print "main(" args ")\n{\n"; }' 

輸出:關於awk部分

main(int argc,char *argv[]) 
{ 

詳情:

BEGIN { args=""; nb=0; }; # Init Variables 
/(main\()argc, argv\)/,/\{/ { # for lines matching 'main' to line matching '{' 
    if (!/^(main|\{).*$/) { # if we're not on the main or { line 
    tmp=$0; # copy the match 
    sub(/;/,"",tmp); # remove the trailing ; 
    if (nb) { # if we're not on the first arg, concat with preceding separed by , 
     args=(args "," tmp); 
     nb+=1; 
    } else { # it is the first arg, just assign 
     args=tmp; 
     nb+=1; 
    } 
    }; 
} 
END { print "main(" args ")\n{\n"; } # we finished matching, print the result. 

這僅僅是你的例如,如果你需要一些更復雜的東西,你應該如果需要,ld能夠使用匹配組和$ 1 $ 2作爲函數名稱。

編輯:我讓你擴展它以滿足你在文件中替換的特殊需要。