This is a read-only archive!

Vim regex - remove kind-of-matching lines

I have a file where every line starts with a number (followed by whitespace and a bunch of other stuff). Every number appears on either one or two lines, and if two, the second line always has a b after the number.

I need to delete every line for which there's a corresponding b line. But if there's no corresponding b line I want to leave the original line there.

Before:

123 foo bar
456 blarg
789 quux
123b foo baz
789b quux blurble

After:

123b foo baz
456 blarg
789b quux blurble

Except in my real file, I have a thousand lines and it'd take a year to do by hand. Vim to the rescue:

:sort
:%s/^\v((\d+).*\n)(\2b.*)/\3/

And that is why Vim is awesome. Can you think of a shorter way to do this, in Vim or Emacs?

June 20, 2010 @ 3:49 PM PDT
Cateogory: Programming
Tags: Vim, Regex

2 Comments

Jim
Quoth Jim on June 21, 2010 @ 1:18 AM PDT

Shorter in lines or shorter in time? ;)

Brian
Quoth Brian on June 21, 2010 @ 2:00 AM PDT

Shorter to write, since runtime is in milliseconds for my tiny files.