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.
In Vim, you can find and replace text using the :substitute ( :s) command. To run commands in Vim, you must be in normal mode, the default mode when starting the editor. To go back to normal mode from any other mode, just press the ‘Esc’ key. The general form of the substitute command is as follows:
This can be achieved by the following vim substitution command. Range: 4,$ – 4th line to last line. Pattern to Replace – \=submatch (0) + 1 – gets the matched pattern and adds 1 to it.
You can perform interactive find and replace using the ‘c’ flag in the substitute, which will ask for confirmation to do substitution or to skip it as explained below. In this example, Vim editor will do a global find the word ‘awesome’ and replace it with ‘wonderful’. But it will do the replacement only based on your input as explained below.
Vi and Vim Editor: 12 Powerful Find and Replace Examples Example 1. Substitute all occurrences of a text with another text in the whole file Example 2. Substitution of a text with another text within a single line Example 3. Substitution of a text with another text within a range of lines
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
:%s/(a\|b\|c\|d\|e\|f)/\U\0/g
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With