Grim Fandango
Grim Fandango

Reputation: 2426

how to grep for 'vector' but not 'std::vector'

I've spotted a using namespace std; in a common header in our code, and I want to remove it.

Consequently, I need to replace all occurrences of vector in my code with std::vector.

I need to write an expression to grep it, that ignores the following cases:

std::vector
// comment with a vector
"string with a vector"

so that I don't end up replacing them like

std::std::vector
// comment with a std::vector
"string with a std::vector"

So far, I've managed to ignore the ''std::vector'' case using the expression

grep "^[^:]*vector" *.h

But I have problems composing negations, like:

can anybody help ?

Upvotes: 1

Views: 167

Answers (4)

zennehoy
zennehoy

Reputation: 6846

Unless you are using vector a lot, you could just remove the using declaration and manually go through the error messages. Typically you'll only need to change places where you instantiate a vector, which shouldn't be that often.

Upvotes: 2

James Kanze
James Kanze

Reputation: 153909

The way I usually do this is to globally replace \<vector\> with std::vector, then to globally replace \<std::std:: with std::.

Upvotes: 1

nvoigt
nvoigt

Reputation: 77294

You might call it cheating, but I'd just replace all std::vector by std::fector, replace all vector by std::vector and then replace all std::fector back to std::vector.

It's not cool, but for a one time solution it probably solves your problem faster than building a complicated expression will. Thinking about the expression alone takes longer than doing just it.

Make sure your program does not use an std::fector though :)

Upvotes: 4

fedorqui
fedorqui

Reputation: 289595

Given this input

$ cat a
std::vector
// comment with a vector
"string with a vector"
replace this vector

You need to pipe grep so that they are AND. Otherwise with egrep "condition1|condition2" they would be OR.

       skip :vector        skip starting with "    skip starting with /
            ----                   -----                 -----
$ grep "^[^:]*vector" a | grep "^[^\"]*vector"   |     grep "^[^/]"
replace this vector

Upvotes: 2

Related Questions