Does Vim replace a word list with the same word list?

I need to substitute a list of words with the same long list of words.

So, for example, you have: "A", "b", "c", "g", "d", "e"

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

I know how to find each line using a regular expression: (A \ | b \ | c \ | d \ | e \ | e)

I know that you can make a global replacement for each word. But when the word length becomes large, this approach will become inexhaustible and inelegant.

Is there a way to somehow make one global replacement? Similar to:

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

I am not sure if this is possible.

+6
vim regex replace substitution
source share
2 answers

You can use the dictionary of elements mapped to their replacements, and then use it on 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 squeeze this into one line, you can use a literal with letters.

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

The specific example that you specified for uppercase letters will be easier to do as

 :%s/[ae]/\U\0/g 
+9
source share

:% s / (a ​​\ | b \ | c \ | d \ | e \ | e) / \ U \ 0 / r

+2
source share

All Articles