我正在清理一个大型 C++ 代码库,其中我需要将“vector”类型的所有变量更改为“std::vector”。跳过代码中的#include 和注释。最重要的是,如果表达式已经写成“std::vector”,不要将它转换为“std::std::vector”
那是:
#include <vector>
vector<Foo> foolist;
typedef vector<Foo> FooListType;
std::vector<Foo> otherfoolist;
int main()
{
// this vector is for iteration
for (vector <Foo>::iterator itor = foo.begin...)
转换为
#include <vector>
std::vector<Foo> foolist;
typedef std::vector<Foo> FooListType;
std::vector<Foo> otherfoolist;
int main()
{
// this vector is for iteration
for (std::vector<Foo>::iterator itor = foo.begin...)
到目前为止,我已将其范围缩小到两个 sed 命令
sed -r 's/vector\s{0,1}</std::vector</g' < codefile > tmpfile
sed 's/std::std/std/' < tmpfile > codefile
第一个 sed 匹配 "vector< 和 "vector <"并转换为 "std::vector<"。
第二个 sed 修复了将“std::vector<”转换为“std::std::vector<”的副作用。
如何合并上面两个不同的正则表达式,以便我可以使用单个 sed 命令来正确修复代码。
我试过在网上阅读关于前瞻和后视的内容,但我的眼睛开始烧焦了。
最佳答案
您可以使第一个正则表达式也匹配可能的 std::
通过使用
sed -r 's/[std:]*vector\s{0,1}</std::vector</' < codefile > tmpfile
顺便说一句:您可以通过添加
-i
来进行适当的更改并将文件作为命令行参数传递:sed -i -r 's/[std:]*vector\s{0,1}</std::vector</' codefile
关于匹配短语的正则表达式,除非它已经加前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11464121/