0

I wish to find lines containing a digit string only and modify each match by putting it in between a pair of square brackets ([..]) in Vim.

e.g. Original text

10001
hostname1
hostname2
10002
hostname3
hostname4
10003
hostname5
hostname6
...

Change it to:

[10001]
hostname1
hostname2
[10002]
hostname3
hostname4
[10003]
hostname5
hostname6
...

I can catch each digit lines using regex:

^\d*$

but don't know how to put the result in between [..] in Vim. Any help will be appreciated. Thank you!

  • Do not know if this helps since I don't use vim, but in others text editors, in this case xed, this work: find (^\d+$) replace [\1] – guillermo chamorro Sep 26 '19 at 21:12
  • 1
    See this answer (maybe a duplicate). You only need to insert your regex and /[&]/ as the replacement. – Freddy Sep 26 '19 at 21:29
1

Try this one:

:%s/\(^\d*$\)/[\1]/
  • Thank you guillermo! This works, too! Am I right that the search term has to be grouped (...) in order for it to work? – cody Sep 27 '19 at 0:50
  • 1
    @cody You could also use & to reference the whole match: :%s/^\d*$/[&]/, that's what I meant in my comment. But if you only need a part of a pattern, then yes, groups and backreferences is the way to do it. – Freddy Sep 27 '19 at 1:09
  • @Freddy thank you so much! that's even easier to grip! – cody Sep 27 '19 at 1:12
2

You can substitute the number string and carry it forward into the replacement string.

%s/^\(\d*\)$/\[\1\]/
  • Thank you bahua. It works! – cody Sep 27 '19 at 0:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.