注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

dp: 生活的脚步,进步的点滴...

Cam、DSP、FPGA、PM、Life、More ...

 
 
 

日志

 
 

Vim: g + norm  

2013-07-30 14:44:47|  分类: |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

My recent favorite vim trick is g + norm. Look in :h g and :h norm to see what these do. Basically g will search all lines in a file for some pattern, and then do something on those lines. norm will take a string of text as an argument and process that string as though you were pressing the keys in vim yourself, starting in Normal mode.

Combined, you can do some neat things. For example to search for all lines that start with a number, and then add a semi-colon to the end of just those lines:

:g/^\d/norm A;

Note that you need to use i, A, o, or some other way of getting into Insert mode if you want to add text.

One of my favorites (I think I read this on some other site one day) is to find every line containing some text and move those lines to the end of the text file. Sort of an ad-hoc partial way of sorting a file:

:g/some text/norm ddGp

All the vim movement commands work too, so to find every line that has a ", move to the end of the line, move 3 characters back to the left and add a ~:

:g/"/norm $hhhi~

You can move between lines or add lines to the file too, which makes things interesting. What if you start with this text file:

1
2
3
4
5

And you do this:

:g/\d/norm o999

Happily this does not blow up into infinite recursion, because vim always makes two passes through the file (one to mark the lines to operate on; a second to actually operate on them); you end up with

1
999
2
999
3
999
4
999
5
999

Vim has a really harsh learning curve. I don't think I discovered :g at all for a year, and didn't discover norm for a while after that. Vim will pay off a lot if you stick with it long-term.

 

This is amazingly powerful and short :g/20/d

It simply says find any line with a 20 in it and run the ex command to delete the line. It has a sick counterpart in :v/20/d (think if it a grep -v) which runs the ex command to delete any line that does not have a 20 in it. This maps basically to your g + norm as :g/20/norm dd

I am trying to find all of the ex commands but there is so much web noise that finding a good basic ex reference is difficult.

Try :h ex-cmd-index or look here online.

 
Came across this gem recently

:g/matchstring/y A

and it pulls all lines matching into one Register...

Copy and move can be done with ex commands c and m:

copy to end of file

    :g/search/c$

move to end of file

    :g/search/m$
 

如何在norm中输入ESC键?

在输入命令时,先按CTRL和V,然后再按ESC键即可,显示为^[。

  评论这张
 
阅读(392)| 评论(0)
推荐

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2016