Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

vim - Search and delete multiple lines

In vim

:g/George Bush/d

deletes all lines with George Bush.

What if I wanted to delete 5 lines below that start with George Bush?

Another realistic example would be to find all DEBUG in a log4net log and delete up to the end of stack trace (which I know will be another 10 lines below it)

question from:https://stackoverflow.com/questions/2070120/search-and-delete-multiple-lines

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The :global command is your friend - learn it well. It lets you run arbitrary :ex commands on every line that matches a regex. It abbreviates to :g.

To delete all lines that match "George Bush":

:g/George Bush/ d

The command that follows can have its own address/range prefix, which will be relative to the matched line. So to delete the 5th line after George Bush:

:g/George Bush/ .+5 d

To delete the DEBUG log entries:

:g/DEBUG/ .,+10 d

If you knew the stack trace was variable length but always ended at a blank line (or other regex):

:g/DEBUG/ .,/^$/ d

You can also execute a command on every line that does NOT match with :g!. e.g. to replace "Bush" with "Obama" on every line that does not contain the word "sucks":

 :g!/sucks/ s/Bush/Obama/

The default command is to print the line to the message window. e.g. to list every line marked TODO:

 :g/TODO

This is also useful for checking the regex matches the lines you expect before you do something destructive.

You can chain multiple commands using "|". e.g. to change Bush to Obama AND George to Barack on every line that does not contain "sucks":

 :g!/sucks/ s/Bush/Obama/g | s/George/Barack/g

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...