Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim substitution of a list of words with another same length list of words?

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.

like image 801
Trevor Boyd Smith Avatar asked Jun 10 '09 22:06

Trevor Boyd Smith


People also ask

How do I use the substitute command in Vim?

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:

How do I replace a line with another line in Vim?

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.

How to perform interactive find and replace in Vim?

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.

Which is an example of a find and replace in Vivi?

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


Video Answer


2 Answers

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
like image 199
Brian Carper Avatar answered Oct 26 '22 22:10

Brian Carper


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

like image 45
Igor Krivokon Avatar answered Oct 26 '22 22:10

Igor Krivokon