Perl replace space on tab

I would like to replace each of the two spaces from the beginning of each line with a tab. I tried the following:

s/^(\s{2})+/\t/gm;

he did not work.

+5
source share
4 answers

If you read the file line by line:

$line =~ s/\G[ ]{2}/\t/g;

If you deleted the whole file:

$file =~ s/(?:\G|^)[ ]{2}/\t/mg;
+5
source

How about this ?

my $test_string = "  some test stuff\ndivided to\n  provide the challenge";
$test_string =~ s/^[ ]{2}/\t/gm;
print $test_string;

Explanation: It \s’s actually not a single alias of a symbol, but a class of “whitespace”: it includes both \n\, and \t. If you want to replace only spaces, use spaces in your regular expressions; setting a character class (and not just /^ {2}/...for me is more readable (and will not break into /x modifier ).

, , +.

UPDATE: , , :

$test_string =~ s#^((?:[ ]{2})+)#"\t" x (length($1)/2)#gme;

... \G , ikegami.

+2

, + " " \s{2}, " ". , .

#! /usr/bin/env perl

use strict;
use warnings;

for (0 .. 10) {
  $_ = " " x $_;
  printf "%-13s %s\n", "[$_]:", /^(\s{2})+$/ ? "match!" : "no match.";
}

:

[]:           no match.
[ ]:          no match.
[  ]:         match!
[   ]:        no match.
[    ]:       match!
[     ]:      no match.
[      ]:     match!
[       ]:    no match.
[        ]:   match!
[         ]:  no match.
[          ]: match!

, TAB .

. - /m /g , , , , . TAB.

#! /usr/bin/env perl

use strict;
use warnings;

$_ = <<EOText;
   Three
  Two
    Four
     Five
Zero
 One
EOText

s/^  /\t/mg;

# for display purposes only
s/\t/\\t/g;

print;

:

\t Three
\tTwo
\t  Four
\t   Five
Zero
 One

, s/// . TAB.

, . ,

$ perl -pe 's/^  /\t/' input-file >output-file

$ perl -i.bak -pe 's/^  /\t/' input-file
+2

/m lookbehind. , - , , , \m

$_ = "  123\n  456\n  789";
s/(?:(?<=^)|(?<=\n))\s{2}/\t/g;
print $_;

/g double whitespace \s{2}, (?<=^) (?: .. | .. ), (?<=\n) \t.

+1
source

All Articles