Remove everything except regex match in Vim

前端 未结 4 554
深忆病人
深忆病人 2020-11-29 04:22

My specific case is a text document that contains lots of text and IPv4 addresses. I want to remove everything except for the IP addresses.

I can use :vglobal<

4条回答
  •  独厮守ぢ
    2020-11-29 04:54

    :set nowrapscan
    :let @a=""
    gg0qac/\v(\d{1,3}\.){3}\d{1,3}//e+1@aq@adG
    

    Explanation:

    1. set nowrapscan disables ability to seek «past the end of file».
    2. let @a="": empty the a register.
    3. gg0: go to the first column (0) of the first line (gg).
    4. qa: start writing macros.
    5. c/{pattern}: change until pattern.
    6. c{motion}: replace text with newline (here {motion} is /{pat}).
    7. //e+1: search for last pattern, go one character left past its end (wraps around a newline, but if your lines looks like this: IPIP, there may be problems).
    8. @a: execute @a macros (it is empty when you are recording it, but when you are finished it will repeat steps 1-7 until it gets an error).
    9. q: end recording @a.
    10. @a: execute @a macros.
    11. dG: delete to the end of file.

提交回复
热议问题