Vim Magic: removing duplicate lines with shell filtering and macros

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

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
"open new split and paste
"delete [ , ]
"filter through sort/uniq -d to only get duplicate lines
:%!sort | uniq -d
"switch to original window
"start recording a macro in register a
    "back to scratch window
    "jump to first line, delete
    "jump back to main window
    "search for the thing I just deleted (backspace the newline char at end)
    "delete it
"stop recording macro
"repeat macro 99 times. there are only 48 lines, but when it finishes the last one,
"it errors out and just stops the loop.

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.