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!

2
  • 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] Commented Sep 26, 2019 at 21:12
  • 1
    See this answer (maybe a duplicate). You only need to insert your regex and /[&]/ as the replacement.
    – Freddy
    Commented Sep 26, 2019 at 21:29

2 Answers 2

3

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

%s/^\(\d*\)$/\[\1\]/
0
2

Try this one:

:%s/\(^\d*$\)/[\1]/
3
  • Thank you guillermo! This works, too! Am I right that the search term has to be grouped (...) in order for it to work?
    – cody
    Commented Sep 27, 2019 at 0:50
  • 2
    @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
    Commented Sep 27, 2019 at 1:09
  • @Freddy thank you so much! that's even easier to grip!
    – cody
    Commented Sep 27, 2019 at 1:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .