zoukankan      html  css  js  c++  java
  • Vim,Delete all lines containing a pattern

    http://vim.wikia.com/wiki/Delete_all_lines_containing_a_pattern


    The ex command g is very useful for acting on lines that match a pattern. You can use it with the d command, to delete all lines that contain a particular pattern, or all lines that do not contain a pattern.

    For example, to delete all lines containing "profile" (the first command is optional; it shows the lines that the second command will delete):

    :g/profile
    :g/profile/d
    

    More complex patterns can be used, such as deleting all lines that are empty or that contain only whitespace:

    :g/^s*$/d
    

    To delete all lines that do not contain a pattern, use g!, like this command to delete all lines that are not comment lines in a Vim script:

    :g!/^s*"/d
    

    Note that g! is equivalent to v, so you could also do the above with:

    :v/^s*"/d
    

    The next example shows use of | ("or") to delete all lines except those that contain "error" or "warn" or "fail" (:help pattern):

    :v/error|warn|fail/d
    

    See alsoEdit

    CommentsEdit

    Can we remove all even numbered lines in a file using this feature. can we do some kind of math in the pattern. (ex: =line(".") % 2)

    Not really, but you can do that in two steps:

    :g/.*/if line('.')%2|call setline(line('.'), '===delete===')|endif
    :g/^==delete==$/d
    

    If you simply put delete inside the if statement all the lines will be deleted. Much faster solution is to record a macro "ddj" and play it over the file. You could delete lines from several different ranges:

    :let range = range(10,15)+range(20,25)+range(30,35)
    :g/.*/if index(range, line('.')) != -1|call setline(line('.'), '===delete===')|endif
    :g/^===delete===$/d
    

    But again I think the faster way to do that is to use :[range]d several times.

  • 相关阅读:
    Leon-ai on WSL
    自动化测试工具
    创建自己的Spring Boot Starter
    Spring Boot内嵌Tomcat session超时问题
    Spring Boot
    Spring Cloud
    Socket编程之Tomcat模拟_采坑汇总
    访问者模式
    模版模式
    策略模式
  • 原文地址:https://www.cnblogs.com/threef/p/3229813.html
Copyright © 2011-2022 走看看