A regular expression expression that matches the phrase if there was no prefix already

I am clearing a large C ++ code base where I need all the variables of type "vector" that need to be changed to "std :: vector". Skipping #include and comments in code. And most importantly, if the expression is already written as "std :: vector", do not convert it to "std :: std :: vector"

I.e:

#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...) 

Converts to

 #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...) 

So far I have narrowed down to two sed commands

 sed -r 's/vector\s{0,1}</std::vector</g' < codefile > tmpfile sed 's/std::std/std/' < tmpfile > codefile 

The first sed matches the vector <and "vector <" and converts to either "std :: vector <".

The second sed captures the side effect of converting "std :: vector <" to "std :: std :: vector <".

How can I combine two different regular expression expressions so that I can have a single sed command that corrects the code correctly.

I tried reading online about lookahead and lookbehind, but my eyes start to burn.

+4
source share
3 answers

You can make the first regex also match std:: using

 sed -r 's/[std:]*vector\s{0,1}</std::vector</' < codefile > tmpfile 

btw: you can make changes in place by adding -i and simply passing the file as a command line parameter:

 sed -i -r 's/[std:]*vector\s{0,1}</std::vector</' codefile 
+3
source

This may work for you (GNU sed):

 sed -i 's/\(^\|[^<:]\)\(vector\s*<\)/\1std::\2/g' file 
+2
source

If your version of sed does not support extended regular expressions, you can use perl:

perl -lane ' if (!/^\s*#include/) {s!(?:std::)?vector!std::vector!g;} print; ' < codefile > tmpfile

this will work in such cases: vector<vector<Foo>> otherfoolist;

see also this answer: fooobar.com/questions/150237 / ...

+1
source

All Articles