Vim Magic: removing duplicate lines with shell filtering and macros

by mattboehm featured
GNU/Linux ◆ screen ◆ bash 4802 views

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 <c-r><c-r>” but here this wasn’t an issue.

More by mattboehm

untitled 00:51

by mattboehm

untitled 00:31

by mattboehm

untitled 72:31

by mattboehm

See all