F. Rakes
F. Rakes

Reputation: 1537

Regex deleting all lines except last occurence of a pattern

I want to delete all lines that match a pattern but the last occurrence. So assume we have this text:

test a 043
test a 123
test a 987 
test b 565

The result I'm aiming for is this:

test a 987 
test b 565

Is it possible to compare strings like that with just regex in vim? This is also assuming the a and b in this example are dynamic ((test\s\w\s(.*)).

Upvotes: 2

Views: 174

Answers (1)

anubhava
anubhava

Reputation: 786011

You will need a lookahead regex in vim for this:

:g/\v(^test \w+)(\_.*\1)@=/d

RegEx Breakup:

\v            # very magic to avoid escapes
(             # capturing group #1 start
   ^test \w+  # match any line starting with test \w+
)             # capturing group #1 end
(\_.*\1)@=    # positive lookahead to make sure there is at least one of \1 below

Upvotes: 4

Related Questions