0

I have here a sample text file called employees.txt. It contains the name, streets and cities of the employees.

My question is: How can I replace all city instances of "Victoria" with "City of Victoria". Only the city is affected, not places like Victoria Drive or people like Ashley Victoria?

I hope someone can help me.

  • For this you need to come up with a situations where all Victoria are distinguishable from all other "other word+Victoria+other word". Otherwise this will be impossible. Alternative: replace all and then replace all those that have an extra word? Is that an option? Basically what I am asking.... are those 2 the exception or is there more you want to skip? – Rinzwind May 26 '22 at 18:58

3 Answers3

1

You can tell vim to ask for confirmation:

:%s/Victoria/City\sof\sVictoria/gc
  • the %s replaces, the g does it globally, the c asks for confirumatiom
  • the \s is for a space.

That might be the quickest but does involve some manual work.

If those are the only 2 this would work too:

:%s/Victoria/City\sof\sVictoria/g
:%s/City\sof\sVictoria\sDrive/City\sof\sVictoria/g
:%s/Ashley\sCity\sof\sVictoria/Ashley\sVictoria/g

but if there are more of these this can become a long list. And do make a backup before you do this ;)

Rinzwind
  • 299,756
1

You seem to be asking about regular expression lookaround assertions

At least in vim (vi improved) , you can use \@! for negative lookahead and \@<! for negative lookbehind. So for example to match Victoria that is not preceded by Ashley (Ashley-space):

\(Ashley \)\@<!Victoria

whereas to match Victoria that is not followed by Drive (space-Drive):

Victoria\( Drive\)\@!

Putting these together:

 :s/\(Ashley \)\@<!Victoria\( Drive\)\@!/City of &/g

where & on the RHS backsubstitutes the matching Victoria. Generalizing to any capitalized "words" before and after Victoria:

:s/\([[:upper:]][[:alpha:]-]* \)\@<!Victoria\( [[:upper:]][[:alpha:]-]*\)\@!/City of &/g

See also:

steeldriver
  • 136,215
  • 21
  • 243
  • 336
0

Another way: (manual)

Search for Victoria:

/Victoria

If it matches your requirements, enter insert mode (i) then type City of

Then in command mode go to next find (n), and if it matches strike the point (.) it will insert City of again, if it does not match go to next find and so on so forth ....