views:

378

answers:

2

I need to substitute a list of words with with an equally long list of words.

So for example you have: "a","b","c","d","e","f"

And you want to replace each word with the uppercase version of each word: "A","B","C","D","E","F"

I know how to find each string using the regex: (a\|b\|c\|d\|e\|f)

I know you could do a global substitution for each word. But when the length of the words gets large this approach would become un-wieldly and inelegant.

Is there a way to somehow do one global substitution? Similar to:

:%s/\(a\|b\|c\|d\|e\|f\)/INSERT_REPLACEMENT_LIST/

I am not sure if this is even possible.

+7  A: 

You can use a dictionary of items mapped to their replacements, then use that in the right side of the search/replace.

:let r={'a':'A', 'b':'B', 'c':'C', 'd':'D', 'e':'E'}
:%s/\v(a|b|c|d|e)/\=r[submatch(1)]/g

See :h sub-replace-\= and :h submatch(). If you want to cram that into one line, you could use a literal dictionary.

:%s/\v(a|b|c|d|e)/\={'a':'A','b':'B','c':'C','d':'D','e':'E'}[submatch(1)]/g

The specific example you gave of uppercasing letters would be more simply done as

:%s/[a-e]/\U\0/g
Brian Carper
s/\(\a\+\)/\U\0/g to change sequences of alphabetical characters to upper case.
Sinan Ünür
If you find yourself doing this often, you define a vim function for this (http://stackoverflow.com/questions/765894/can-i-substitute-multiple-items-in-a-single-regular-expression-in-vim-or-perl/766093#766093)
rampion
@Brian, what is the "\v" in your substitution?
Trevor Boyd Smith
@Brian, when I do my substitutions I have to put a backslash to escape the '(', '|', and ')' characters. Why do you not have to? Or is your syntax wrong?
Trevor Boyd Smith
The \v puts the regex into "very magic" mode, which lets you avoid backslashes. See :h /\v
Brian Carper
+2  A: 

:%s/(a\|b\|c\|d\|e\|f)/\U\0/g

Igor Krivokon