mattboehm

Vim Magic: removing duplicate lines with shell filtering and macros

by mattboehm 2013-11-20 06:41:19 UTC
  • Linux / bash / screen
  • 721

See the embedding docs for more options.

While working on a PR for vim-lint, I ran into an interesting problem: a file that lists ex commands had some duplicates, as it contained both abo[veleft] and aboveleft even though only the first was necessary.

Here's how I fixed it:

"copy all text
ggyG 
"open new split and paste
:vnew
p
"delete [ , ]
:%s;\[\|\];;g
"filter through sort/uniq -d to only get duplicate lines
:%!sort | uniq -d
"switch to original window
<c-w>w
"start recording a macro in register a
qa
    "back to scratch window
    <c-w>w
    "jump to first line, delete
    ggdd
    "jump back to main window
    <c-w>w
    "search for the thing I just deleted (backspace the newline char at end)
    /<c-r>"<backspace><enter>
    "delete it
    dd
"stop recording macro
q
"repeat macro 99 times. there are only 48 lines, but when it finishes the last one,
"it errors out and just stops the loop.
99@a

edit: I had a bug; I should have put a $ at the end of the pattern being searched for. Ideally I'd use " but here this wasn't an issue.