Enclose multiple lines in quote Vim

regular expressiontext processingvim

I have blocks of the following form:

    String that is not supposed to be enclosed in quotes
    String that is supposed to be enclosed in quotes

    String that is not supposed to be enclosed in quotes
    String that is supposed to be enclosed in quotes

    String that is not supposed to be enclosed in quotes
    String that is supposed to be enclosed in quotes

    String that is not supposed to be enclosed in quotes
    String that is supposed to be enclosed in quotes

I need to put the lines that state that they are supposed to be enclosed in quotes in quotes:

    String that is not supposed to be enclosed in quotes
    "String that is supposed to be enclosed in quotes"

    String that is not supposed to be enclosed in quotes
    "String that is supposed to be enclosed in quotes"

    String that is not supposed to be enclosed in quotes
    "String that is supposed to be enclosed in quotes"

    String that is not supposed to be enclosed in quotes
    "String that is supposed to be enclosed in quotes"

Is there a semi-automatic way of doing this with Vim? I thought that a possible solution might involve the g command.

Best Answer

Using regular expressions:

:%s/.*is supposed.*/"&"/

If by "semi-automatic" you mean you would like to be prompted before each substitution, just add the /c modifier to the substitution pattern:

:%s/.*is supposed.*/"&"/c

Explanation

  • :%s means apply this substitution to all lines in the current buffer
  • The pattern we match is any line containing the words is supposed (if some other lines contain the words "is supposed" without "to be enclosed in quotes" following them, you can always change the pattern to .*is supposed to be enclosed in quotes.*
  • The string we use to replace the matched pattern is "&", where & stands for whatever was matched by the pattern.
Related Question