How can I repeat the Perl regex until there are no changes left?

I am trying to write a simple command line script to fix some spaces and require replacing the occurrence of two spaces with a tab, but only if it appears at the beginning of the line (prefix only with other tabs.)

I came up with s/^(\t*) /\1\t/g; , which works fine if I run a few passes, but I don't know enough about perl to know how to loop until the string changes, or if there is a regular expression to handle it.

My only thought was to use lookbehind, but it cannot be of variable length. I would be open to a solution without regular expressions if it was short enough to fit into a fast command line script.

For reference, the current perl script is executed as follows:

 perl -pe 's/^(\t*) /$1\t/g' 
+4
source share
4 answers

Check out a very simple question

You can use 1 while s/^(\t*) /$1\t/g; to repeat the pattern until changes are made.

+6
source

or

 perl -pe 's{^(\t*)(( )+)}{$1 . "\t" x (length($2)/length($3))}e' 
+3
source

Supports mixing spaces and tabs:

 perl -pe'($i,$s)=/^([ \t]*)([.*])/s; $i=~s/ /\t/g; $_="$i$s";' 
+1
source

This is Perl, so you do not need to do a loop. Instead, you can simply evaluate the replace expression as follows:

 my $tl = 4; s{ ( \t* ) ( [ ]* ) } { my $l=length( $2 ); "$1" . ( "\t" x int( $l / $tl )) . ( ' ' x ( $l % $tl )) }ex ; 
0
source

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


All Articles