[英]sed need something like a backreference for append
我有一堆C ++源文件,我希望在其中插入一個簡單的函數定義(大約6行)。 該定義應立即出現在另一個函數定義之后。
使用對此問題的公認答案: sed匹配多行,然后追加 ,我可以插入平凡的函數定義,但是無法將其范圍限定為適當類的成員。
測試代碼:
void object::func1()
{
std::cout << "func1" << std::endl;
}
插入非成員函數:
james@scrapyard:~/Projects$ sed '/func1()$/,/^}/!b;/^}/a \\nint func2()\n{\n\ \ \ \ return 0;\n}' func1.cc
void object::func1()
{
std::cout << "func1" << std::endl;
}
int 1::func2()
{
return 0;
}
嘗試對類名進行分組並按如下所示使用反向引用將導致1::func2
而不是object::func2
。
sed '/\\([[:alnum:]]\\+\\)::func1()$/,/^}/!b;/^}/a \\\\nint \\1::func2()\\n{\\n\\ \\ \\ \\ return 0;\\n}' testcode.cc
如果我使用替代命令而不是附加命令,它將起作用,但是替代命令被/,/
破壞/,/
導致:
sed: -e expression #1, char 33: unknown option to
s'的sed: -e expression #1, char 33: unknown option to
有可能在sed中嗎?
這可能對您有用(GNU sed):
sed '/^.* \([^:]*::\)func1()$/{h;x;s//\nint \1func2()\n{\n return 0;\n}/;x};//,/^}$/{/^}$/G}' file
這將查找函數定義,然后在保留空間(HS)中構建平凡的函數。 遇到函數結尾時,它將附加HS。
向后引用只能引用同一表達式中的捕獲。 !b
之后的分號結束第一個表達式。 保持空間可以將字符串從一個表達式傳遞到另一個表達式。
sed '/\\w\\+::func1()$/,/^}/!b;/\\w\\+::func1()$/{h;s/^\\w*\\s\\+\\(\\w\\+\\)::func1()$/\\1/;x};/^}/ {g;s/.*/}\\n\\nint &::func2()\\n{\\n\\ \\ \\ \\ return 0;\\n}/}' testcode.cc
Sed一次將一行讀入模式空間,在該空間中,像s///
這樣s///
命令將在此運行。 線條可以在保留空間中放置一旁,稍后再返回到圖案空間中。
sed '
/\w\+::func1()$/,/^}/!b # Ignore lines outside the target function.
/\w\+::func1()$/ { # On the line declaring the function,
h # save that line to the hold space;
s/^\w*\s\+\(\w\+\)::func1()$/\1/ # replace the function with its class name;
x # save the class name and restore the function declaration.
}
/^}/ { # at the end of the target function
g # retrieve the class name
# substitue the class name into the new function
s/.*/}\n\nint &::func2()\n{\n\ \ \ \ return 0;\n}/
}
' testcode.cc
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.