How to exactly repeat the n matched pattern in the result line

How to exactly repeat the n matching pattern in the result line?

Example if I have the following text:

++ '[' -f /etc/bashrc ']' ++ . /etc/bashrc +++ '[' '[\ u@ \h \W]\$ ' ']' +++ '[' -z 'printf "\033]0;% s@ %s:%s\007" "${USER}" "${HOSTNAME%%.*}" "${PWD/#$HOME/~}"' ']' +++ shopt -s checkwinsize +++ '[' '[\ u@ \h \W]\$ ' = '\s-\v\$ ' ']' +++ shopt -q login_shell +++ '[' 506 -gt 199 ']' ++++ id -gn 

Now I want to replace each "+" with 3 spaces, but this can only happen at the beginning of the template. I would use :<range>s/^<pattern> :%s/+/ /g , but if the rest of the text was "+", I would just mess it up.

Question: How to compare each + at the beginning and repeat the same number of + found in the result line? Expected Result:

 ^ ++$ -> ^ $ ^ +++$ -> ^ $ ^ +$ -> ^ $ 

thanks

+6
source share
3 answers

Try the following:

 :%s/^+*/\=repeat(' ',strlen(submatch(0)))/ 

submatch(0) contains all matched + at the beginning of the line, strlen counts them. Therefore, for each plus sign at the beginning of the line, three spaces are inserted using repeat .

For more information:

 :help sub-replace-expression :help repeat() :help submatch() :help strlen() 
+8
source

The elegant lookup team for this case is as follows.

 :%s/\%(^+*\)\@<=+/ /g 
+3
source

I think you will have to run the expression several times if this is acceptable ...

You need to run something like this (minus the single quotes that are used to display spaces):

 '^(\s*)+' 

replace with something like (again minus single quotes)

 '$1 ' 

Not all problems that can be solved with regular expressions can be solved with just one regular expression - I'm sure this is one of those cases

This pair of expressions / substitutions should be run once for each plus sign at the beginning of the line with maximum characters (in your example above, this will be four times). NB: as written, this will ruin any lines that should start with spaces and plus signs, so I hope this does not happen anywhere ...

+1
source

Source: https://habr.com/ru/post/922283/


All Articles