22

How do I repeat a character n times in a string used in substitution?

I want to do something like below:

$numOfChar = 10;

s/^\s*(.*)/' ' x $numOfChar$1/;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
chappar
  • 7,275
  • 12
  • 44
  • 57
  • 1
    Do you get any error messages? – tstenner Mar 22 '09 at 08:33
  • Note: Not really *[How can I repeat a string N times in Perl?](https://stackoverflow.com/questions/277485/)* (the search engines can't tell the difference), as this question is about repetition inside a regular expression (or substitution, rather). – Peter Mortensen Aug 23 '23 at 20:11

3 Answers3

28

By default, substitutions take a string as the part to substitute. To execute code in the substitution process you have to use the e flag.

$numOfChar = 10;

s/^(.*)/' ' x $numOfChar . $1/e;

This will add $numOfChar space to the start of your text. To do it for every line in the text either use the -p flag (for quick, one-line processing):

cat foo.txt | perl -p -e "$n = 10; s/^(.*)/' ' x $n . $1/e/" > bar.txt

or if it's a part of a larger script use the -g and -m flags (-g for global, i.e. repeated substitution and -m to make ^ match at the start of each line):

$n = 10;
$text =~ s/^(.*)/' ' x $n . $1/mge;
kixx
  • 3,245
  • 22
  • 19
15

Your regular expression can be written as:

$numOfChar = 10;

s/^(.*)/(' ' x $numOfChar).$1/e;

but - you can do it with:

s/^/' ' x $numOfChar/e;

Or without using regexps at all:

$_ = ( ' ' x $numOfChar ) . $_;
  • Note that this answer no longer applies, because chappar added a \s* to his question after this answer was given. – ysth Mar 22 '09 at 19:49
  • 1
    At the moment none of the answers really apply. But it can be easily fixed. Just change: s/^/' ' x $numOfChar/e; into: s/^\s*/' ' x $numOfChar/e; –  Mar 23 '09 at 02:47
9

You're right. Perl's x operator repeats a string a number of times.

print "test\n" x 10; # prints 10 lines of "test"

To do this inside a regular expression, it would probably be best (a.k.a. most maintainer friendly) to just assign the value to another variable.

my $spaces = " " x 10;
s/^\s*(.*)/$spaces$1/;

There are ways to do it without an extra variable, but it's just my $0.02 that it'll be easier to maintain if you do it this way.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Chris Lutz
  • 73,191
  • 16
  • 130
  • 183