5

How can you replace one match with multiple instances of a character (like \t)?

It's no problem to replace multiple characters with one. But I did not find the answer for the opposite.

For example: I want to change

Items: item1 item2 item3 item4

to

Items:
                item1
                item2
                ...

and for the whitespace I want to use \t tabstop (for example). Something like:

:%s/\s\(item.\)/\r\t{5}\1/g

does not work.

1
  • Curly braces need to be escaped in patterns: \{5}; unless you use \very magic. (But that won't make it work in the replacement part, where you want to use it.) Commented Dec 29, 2016 at 16:26

1 Answer 1

9
  • You are probably best off just hitting dat Tab key 5 times in your example:
    :%s/\s\(item.\)/\r    TabTabTabTabTab    \1/g
    (The tabs display as ^I in the Command-line.)

  • More elegantly, you can have vim repeat that typing for you. But with its ≥7 keystrokes and a bit of thinking effort, this technique is only economical for a bigger number of repetitions or characters to be repeated:
    :%s/\s\(item.\)/\r    Ctrl-f 5a \t Ctrl-c    \1/g

  • The most literal and technical answer to your question is – at the cost of even much more verbose syntax – using \= for substituting by an expression [:help sub-replace-expression], in which you could then employ the repeat() function:
    :%s/\s\(item.\)/\= "\n" . repeat("\t", 5) . submatch(1)/g   (Readability spaces not required.)

Unfortunately, vim does not provide syntactic sugar for repetition (\{5} or otherwise) in the replacement part of the :substitute command; almost none of the special regex syntax for pattern matching [:h pattern-overview] is available for the replacement: :h sub-replace-special


(PS: TabTabTabTabTabTabTabTabTabTabTabTabTabTabTab)

2
  • 1
    the number of "5" was just exemplary. I should have written 15 :) Thanks for the helpfull and comprehensive answer. I really like your idea to use the <c-f> shortcut to generate the command for repetition! (stumpled over this useful shortcut some weeks ago but did't thought about it in this case) Awesome!
    – MacMartin
    Commented Dec 30, 2016 at 6:24
  • @eli, hey, thank you for your nice feedback! :) I'm glad it was helpful! (I updated the PS part to reflect the new number. ;) ) Commented Dec 30, 2016 at 14:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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