Insert a character after (n) characters and repeat(n) times - vim

允我心安 提交于 2021-02-19 03:46:13

问题


Frequently i receive tickets from our support to make a dhcp reservation on isc-dhcp. Some printers(cof,cof HP) print the mac address information on the test page this way: 002481F33A9C ; and obviously the support guys write this way to the Ticket. I want to change to 00:24:81:F3:3A:9C layout and use an efficient way to do a "insert : after 2 characters 4 times".

I know that i can achieve this with macros:

qq     " start recording -> register q
ll     " move the cursor 2 characters right
i      " enter insert mode
:      " insert :
<Esc>  " switch to normal mode and cursor goes 1 character back
l      " move the cursor 1 character right(since insert mode back one character)
q      " stop recording
4@q    " execute macro 4 times

And then this:

host foo {
    hardware ethernet 002481F33A9C;
    fixed-address 192.x.x.x;
}

will be turned into this:

host foo {
    hardware ethernet 00:24:81:F3:3A:9C;
    fixed-address 192.x.x.x;
}

Is there a way to make this on a faster way through the command-line mode and without recording a macro, because we have lots of offices, and passing a vimrc with this macro to all machines(and redundancy ones) could be a pain?

Cheers


回答1:


A possible solution:

:%s/\v(hardware ethernet) (..)(..)(..)(..)(..)(..);$/\1 \2:\3:\4:\5:\6\:\7;/g

Explanation:

  • turn on 'very magic' mode

  • match the string hardware ethernet followed by 12 characters, then semicolon and end-of-line

  • divide the 12 characters into 6 sub-expressions, each made of 2 characters

  • replace the string inserting a colon between each sub-expression




回答2:


you could try this command line in your whole file:

:%s/\v [0-9A-F]{2}\zs[0-9A-F]{10};$/\=substitute(submatch(0),'[0-9A-F]\{2}',":\\0","g")

it looks a bit long, due to the buildin function names. this line will search for this pattern:

(space)[0-9A-F]{16};<EOL>

And add :s. you could try if it works for your real files.



来源:https://stackoverflow.com/questions/16241250/insert-a-character-after-n-characters-and-repeatn-times-vim

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!