0

In our code, we have non-standard naming conventions for our variables. For example, we have a category identifier that are attached to many variables in a file, like: usa_foo, bar_usa, where usa is the category identifier. I'd like to convert all these names with a standard of placing the category id in the end, so usa_foo would turn into foo_usa. Since these variables are often embedded in expressions, they could be followed by a few possible characters, which in this case (hashicorp hcl language), are mostly ", ], , or whitespace. For example, I'd like to turn:

usa_foo = something
something "${var.usa_foo}"
b = [var.usa_foo, var.bar_usa]
bar_usa

into:

foo_usa = something
something "${var.foo_usa}"
b = [var.foo_usa, var.bar_usa]
bar_usa

I know how to do find and replace if I know the character that follows the word, say ". Then it would be

%s/usa_\(\w*\)"\(.*\)/\1_usa"\2/g

However, I'm not sure how I can match multiple ending characters and still do the same thing.

breezymri
  • 3,975
  • 8
  • 31
  • 65
  • 1
    vim has [`\>` as a character for word boundary](https://stackoverflow.com/questions/8404349/in-vim-how-do-you-search-for-a-word-boundary-character-like-the-b-in-regexp). Does that give you enough information? – jeremysprofile Apr 02 '20 at 16:53
  • that works. Thanks @jeremysprofile – breezymri Apr 02 '20 at 17:07
  • Does this answer your question? [In Vim, how do you search for a word boundary character, like the \b in regexp?](https://stackoverflow.com/questions/8404349/in-vim-how-do-you-search-for-a-word-boundary-character-like-the-b-in-regexp) – jeremysprofile Apr 02 '20 at 18:24

1 Answers1

1

Using very magic to avoid backslash

:%s/\v(usa)(_)(foo)/\3\2\1

\v ................... very magic
() ................... regex group with no backslash

NOTE: We keep the second group in the middle, just exchange 1 for 3

Of course, if you have other occurrences at the same line you should add /g

SergioAraujo
  • 11,069
  • 3
  • 50
  • 40