Search code examples
regexvimreplace

How can I replace a pattern only on lines that do or do not contain another pattern?


Say I have a text containing the words red and blue.

How do I replace occurences of the word blue with the word green only in all lines containing the word red?

Likewise how can I replace blue with green in all lines NOT containing the word red?


Solution

  • In general, to execute a command on all lines of a file, you want the :global command, abbreviated :g. The general pattern is :g/pattern/cmd. (Often, the pattern (regex) is abbreviated re and the command is p (print the line), so this becomes :g/re/p and is the origin of the word grep). In this case, the command is s//, so:

    To replace "blue" with "green" in lines that contain "red":

    :g/red/s/blue/green
    

    To do the replacement in lines that do not contain "red":

    :g!/red/s/blue/green