Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

replace

vim

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?

like image 792
Kristian Avatar asked Aug 17 '12 17:08

Kristian


People also ask

How does. replace work in Regex?

To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring. The string 3foobar4 matches the regex /\d. *\d/ , so it is replaced.


1 Answers

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 
like image 168
William Pursell Avatar answered Oct 04 '22 11:10

William Pursell